blob: d4312c8b25339b20952c6e31b567770a58071c08 [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"
David Majnemerfa0f1e62016-08-16 18:48:34 +000019#include "llvm/ADT/SetVector.h"
Rafael Espindolaab73c492014-01-28 16:56:46 +000020#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/StringMap.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000022#include "llvm/IR/ConstantRange.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000023#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Instruction.h"
25#include "llvm/IR/LLVMContext.h"
26#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
Sanjay Patel9da9c762016-03-12 20:44:58 +000041/// Canonicalize metadata arguments to intrinsics.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000042///
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;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +000086 return Store.lookup(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000087}
88
89void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
90 LLVMContext &Context = getContext();
91 MD = canonicalizeMetadataForValue(Context, MD);
92 auto &Store = Context.pImpl->MetadataAsValues;
93
94 // Stop tracking the old metadata.
95 Store.erase(this->MD);
96 untrack();
97 this->MD = nullptr;
98
99 // Start tracking MD, or RAUW if necessary.
100 auto *&Entry = Store[MD];
101 if (Entry) {
102 replaceAllUsesWith(Entry);
103 delete this;
104 return;
105 }
106
107 this->MD = MD;
108 track();
109 Entry = this;
110}
111
112void MetadataAsValue::track() {
113 if (MD)
114 MetadataTracking::track(&MD, *MD, *this);
115}
116
117void MetadataAsValue::untrack() {
118 if (MD)
119 MetadataTracking::untrack(MD);
120}
121
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000122bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
123 assert(Ref && "Expected live reference");
124 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
125 "Reference without owner must be direct");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000126 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000127 R->addRef(Ref, Owner);
128 return true;
129 }
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000130 if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
131 assert(!PH->Use && "Placeholders can only be used once");
132 assert(!Owner && "Unexpected callback to owner");
133 PH->Use = static_cast<Metadata **>(Ref);
134 return true;
135 }
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000136 return false;
137}
138
139void MetadataTracking::untrack(void *Ref, Metadata &MD) {
140 assert(Ref && "Expected live reference");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000141 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000142 R->dropRef(Ref);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000143 else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
144 PH->Use = nullptr;
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000145}
146
147bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
148 assert(Ref && "Expected live reference");
149 assert(New && "Expected live reference");
150 assert(Ref != New && "Expected change");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000151 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000152 R->moveRef(Ref, New, MD);
153 return true;
154 }
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000155 assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
156 "Unexpected move of an MDOperand");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000157 assert(!isReplaceable(MD) &&
158 "Expected un-replaceable metadata, since we didn't move a reference");
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000159 return false;
160}
161
162bool MetadataTracking::isReplaceable(const Metadata &MD) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000163 return ReplaceableMetadataImpl::isReplaceable(MD);
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000164}
165
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000166void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000167 bool WasInserted =
168 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
169 .second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000170 (void)WasInserted;
171 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000172
173 ++NextIndex;
174 assert(NextIndex != 0 && "Unexpected overflow");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000175}
176
177void ReplaceableMetadataImpl::dropRef(void *Ref) {
178 bool WasErased = UseMap.erase(Ref);
179 (void)WasErased;
180 assert(WasErased && "Expected to drop a reference");
181}
182
183void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
184 const Metadata &MD) {
185 auto I = UseMap.find(Ref);
186 assert(I != UseMap.end() && "Expected to move a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000187 auto OwnerAndIndex = I->second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000188 UseMap.erase(I);
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000189 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
190 (void)WasInserted;
191 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000192
193 // Check that the references are direct if there's no owner.
194 (void)MD;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000195 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000196 "Reference without owner must be direct");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000197 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000198 "Reference without owner must be direct");
199}
200
201void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000202 if (UseMap.empty())
203 return;
204
205 // Copy out uses since UseMap will get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000206 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
207 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
208 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
209 return L.second.second < R.second.second;
210 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000211 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith4a4f7852015-01-14 19:56:10 +0000212 // Check that this Ref hasn't disappeared after RAUW (when updating a
213 // previous Ref).
214 if (!UseMap.count(Pair.first))
215 continue;
216
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000217 OwnerTy Owner = Pair.second.first;
218 if (!Owner) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000219 // Update unowned tracking references directly.
220 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
221 Ref = MD;
Duncan P. N. Exon Smith121eeff2014-12-12 19:24:33 +0000222 if (MD)
223 MetadataTracking::track(Ref);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000224 UseMap.erase(Pair.first);
225 continue;
226 }
227
228 // Check for MetadataAsValue.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000229 if (Owner.is<MetadataAsValue *>()) {
230 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000231 continue;
232 }
233
234 // There's a Metadata owner -- dispatch.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000235 Metadata *OwnerMD = Owner.get<Metadata *>();
236 switch (OwnerMD->getMetadataID()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000237#define HANDLE_METADATA_LEAF(CLASS) \
238 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000239 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000240 continue;
241#include "llvm/IR/Metadata.def"
242 default:
243 llvm_unreachable("Invalid metadata subclass");
244 }
245 }
246 assert(UseMap.empty() && "Expected all uses to be replaced");
247}
248
249void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
250 if (UseMap.empty())
251 return;
252
253 if (!ResolveUsers) {
254 UseMap.clear();
255 return;
256 }
257
258 // Copy out uses since UseMap could get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000259 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
260 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
261 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
262 return L.second.second < R.second.second;
263 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000264 UseMap.clear();
265 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000266 auto Owner = Pair.second.first;
267 if (!Owner)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000268 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000269 if (Owner.is<MetadataAsValue *>())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000270 continue;
271
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000272 // Resolve MDNodes that point at this.
273 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000274 if (!OwnerMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000275 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000276 if (OwnerMD->isResolved())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000277 continue;
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000278 OwnerMD->decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000279 }
280}
281
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000282ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000283 if (auto *N = dyn_cast<MDNode>(&MD))
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000284 return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
285 return dyn_cast<ValueAsMetadata>(&MD);
286}
287
288ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
289 if (auto *N = dyn_cast<MDNode>(&MD))
290 return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
291 return dyn_cast<ValueAsMetadata>(&MD);
292}
293
294bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
295 if (auto *N = dyn_cast<MDNode>(&MD))
296 return !N->isResolved();
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000297 return dyn_cast<ValueAsMetadata>(&MD);
298}
299
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000300static Function *getLocalFunction(Value *V) {
301 assert(V && "Expected value");
302 if (auto *A = dyn_cast<Argument>(V))
303 return A->getParent();
304 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
305 return BB->getParent();
306 return nullptr;
307}
308
309ValueAsMetadata *ValueAsMetadata::get(Value *V) {
310 assert(V && "Unexpected null Value");
311
312 auto &Context = V->getContext();
313 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
314 if (!Entry) {
315 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
316 "Expected constant or function-local value");
Dehao Chene0e0ed12016-09-16 18:27:20 +0000317 assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000318 V->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000319 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000320 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000321 else
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000322 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000323 }
324
325 return Entry;
326}
327
328ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
329 assert(V && "Unexpected null Value");
330 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
331}
332
333void ValueAsMetadata::handleDeletion(Value *V) {
334 assert(V && "Expected valid value");
335
336 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
337 auto I = Store.find(V);
338 if (I == Store.end())
339 return;
340
341 // Remove old entry from the map.
342 ValueAsMetadata *MD = I->second;
343 assert(MD && "Expected valid metadata");
344 assert(MD->getValue() == V && "Expected valid mapping");
345 Store.erase(I);
346
347 // Delete the metadata.
348 MD->replaceAllUsesWith(nullptr);
349 delete MD;
350}
351
352void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
353 assert(From && "Expected valid value");
354 assert(To && "Expected valid value");
355 assert(From != To && "Expected changed value");
356 assert(From->getType() == To->getType() && "Unexpected type change");
357
358 LLVMContext &Context = From->getType()->getContext();
359 auto &Store = Context.pImpl->ValuesAsMetadata;
360 auto I = Store.find(From);
361 if (I == Store.end()) {
Dehao Chene0e0ed12016-09-16 18:27:20 +0000362 assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000363 return;
364 }
365
366 // Remove old entry from the map.
Dehao Chene0e0ed12016-09-16 18:27:20 +0000367 assert(From->IsUsedByMD && "Expected From to be used by metadata");
Owen Anderson7349ab92015-06-01 22:24:01 +0000368 From->IsUsedByMD = false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000369 ValueAsMetadata *MD = I->second;
370 assert(MD && "Expected valid metadata");
371 assert(MD->getValue() == From && "Expected valid mapping");
372 Store.erase(I);
373
374 if (isa<LocalAsMetadata>(MD)) {
375 if (auto *C = dyn_cast<Constant>(To)) {
376 // Local became a constant.
377 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
378 delete MD;
379 return;
380 }
381 if (getLocalFunction(From) && getLocalFunction(To) &&
382 getLocalFunction(From) != getLocalFunction(To)) {
383 // Function changed.
384 MD->replaceAllUsesWith(nullptr);
385 delete MD;
386 return;
387 }
388 } else if (!isa<Constant>(To)) {
389 // Changed to function-local value.
390 MD->replaceAllUsesWith(nullptr);
391 delete MD;
392 return;
393 }
394
395 auto *&Entry = Store[To];
396 if (Entry) {
397 // The target already exists.
398 MD->replaceAllUsesWith(Entry);
399 delete MD;
400 return;
401 }
402
403 // Update MD in place (and update the map entry).
Dehao Chene0e0ed12016-09-16 18:27:20 +0000404 assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000405 To->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000406 MD->V = To;
407 Entry = MD;
408}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000409
Devang Patela4f43fb2009-07-28 21:49:47 +0000410//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000411// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000412//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000413
Devang Pateldcb99d32009-10-22 00:10:15 +0000414MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000415 auto &Store = Context.pImpl->MDStringCache;
Benjamin Kramereab3d362016-07-21 13:37:48 +0000416 auto I = Store.try_emplace(Str);
Mehdi Aminicb708b22016-03-25 05:58:04 +0000417 auto &MapEntry = I.first->getValue();
418 if (!I.second)
419 return &MapEntry;
420 MapEntry.Entry = &*I.first;
421 return &MapEntry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000422}
423
424StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000425 assert(Entry && "Expected to find string map entry");
426 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000427}
428
429//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000430// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000431//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000432
James Y Knight8096d342015-06-17 01:21:20 +0000433// Assert that the MDNode types will not be unaligned by the objects
434// prepended to them.
435#define HANDLE_MDNODE_LEAF(CLASS) \
James Y Knightf27e4412015-06-17 13:53:12 +0000436 static_assert( \
437 llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
438 "Alignment is insufficient after objects prepended to " #CLASS);
James Y Knight8096d342015-06-17 01:21:20 +0000439#include "llvm/IR/Metadata.def"
440
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000441void *MDNode::operator new(size_t Size, unsigned NumOps) {
James Y Knight8096d342015-06-17 01:21:20 +0000442 size_t OpSize = NumOps * sizeof(MDOperand);
443 // uint64_t is the most aligned type we need support (ensured by static_assert
444 // above)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000445 OpSize = alignTo(OpSize, llvm::alignOf<uint64_t>());
James Y Knight8096d342015-06-17 01:21:20 +0000446 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000447 MDOperand *O = static_cast<MDOperand *>(Ptr);
James Y Knight8096d342015-06-17 01:21:20 +0000448 for (MDOperand *E = O - NumOps; O != E; --O)
449 (void)new (O - 1) MDOperand;
450 return Ptr;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000451}
452
Naomi Musgrave21c1bc42015-08-31 21:06:08 +0000453void MDNode::operator delete(void *Mem) {
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000454 MDNode *N = static_cast<MDNode *>(Mem);
James Y Knight8096d342015-06-17 01:21:20 +0000455 size_t OpSize = N->NumOperands * sizeof(MDOperand);
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000456 OpSize = alignTo(OpSize, llvm::alignOf<uint64_t>());
James Y Knight8096d342015-06-17 01:21:20 +0000457
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000458 MDOperand *O = static_cast<MDOperand *>(Mem);
459 for (MDOperand *E = O - N->NumOperands; O != E; --O)
460 (O - 1)->~MDOperand();
James Y Knight8096d342015-06-17 01:21:20 +0000461 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000462}
463
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000464MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000465 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
466 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
467 NumUnresolved(0), Context(Context) {
468 unsigned Op = 0;
469 for (Metadata *MD : Ops1)
470 setOperand(Op++, MD);
471 for (Metadata *MD : Ops2)
472 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000473
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000474 if (!isUniqued())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000475 return;
476
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000477 // Count the unresolved operands. If there are any, RAUW support will be
478 // added lazily on first reference.
479 countUnresolvedOperands();
Devang Patela4f43fb2009-07-28 21:49:47 +0000480}
481
Duncan P. N. Exon Smith03e05832015-01-20 02:56:57 +0000482TempMDNode MDNode::clone() const {
483 switch (getMetadataID()) {
484 default:
485 llvm_unreachable("Invalid MDNode subclass");
486#define HANDLE_MDNODE_LEAF(CLASS) \
487 case CLASS##Kind: \
488 return cast<CLASS>(this)->cloneImpl();
489#include "llvm/IR/Metadata.def"
490 }
491}
492
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000493static bool isOperandUnresolved(Metadata *Op) {
494 if (auto *N = dyn_cast_or_null<MDNode>(Op))
495 return !N->isResolved();
496 return false;
497}
498
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000499void MDNode::countUnresolvedOperands() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000500 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000501 assert(isUniqued() && "Expected this to be uniqued");
Sanjoy Das39c226f2016-06-10 21:18:39 +0000502 NumUnresolved = count_if(operands(), isOperandUnresolved);
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000503}
504
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000505void MDNode::makeUniqued() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000506 assert(isTemporary() && "Expected this to be temporary");
507 assert(!isResolved() && "Expected this to be unresolved");
508
Duncan P. N. Exon Smithcb33d6f2015-03-31 20:50:50 +0000509 // Enable uniquing callbacks.
510 for (auto &Op : mutable_operands())
511 Op.reset(Op.get(), this);
512
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000513 // Make this 'uniqued'.
514 Storage = Uniqued;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000515 countUnresolvedOperands();
516 if (!NumUnresolved) {
517 dropReplaceableUses();
518 assert(isResolved() && "Expected this to be resolved");
519 }
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000520
521 assert(isUniqued() && "Expected this to be uniqued");
522}
523
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000524void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000525 assert(isTemporary() && "Expected this to be temporary");
526 assert(!isResolved() && "Expected this to be unresolved");
527
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000528 // Drop RAUW support and store as a distinct node.
529 dropReplaceableUses();
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000530 storeDistinctInContext();
531
532 assert(isDistinct() && "Expected this to be distinct");
533 assert(isResolved() && "Expected this to be resolved");
534}
535
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000536void MDNode::resolve() {
Duncan P. N. Exon Smithb8f79602015-01-19 19:26:24 +0000537 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000538 assert(!isResolved() && "Expected this to be unresolved");
539
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000540 NumUnresolved = 0;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000541 dropReplaceableUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000542
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000543 assert(isResolved() && "Expected this to be resolved");
544}
545
546void MDNode::dropReplaceableUses() {
547 assert(!NumUnresolved && "Unexpected unresolved operand");
548
549 // Drop any RAUW support.
550 if (Context.hasReplaceableUses())
551 Context.takeReplaceableUses()->resolveAllUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000552}
553
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000554void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000555 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000556 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000557
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000558 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000559 if (!isOperandUnresolved(Old)) {
560 if (isOperandUnresolved(New))
561 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000562 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000563 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000564 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000565}
566
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000567void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000568 assert(!isResolved() && "Expected this to be unresolved");
569 if (isTemporary())
570 return;
571
572 assert(isUniqued() && "Expected this to be uniqued");
573 if (--NumUnresolved)
574 return;
575
576 // Last unresolved operand has just been resolved.
577 dropReplaceableUses();
578 assert(isResolved() && "Expected this to become resolved");
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000579}
580
Teresa Johnsonb703c772016-03-29 18:24:19 +0000581void MDNode::resolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000582 if (isResolved())
583 return;
584
585 // Resolve this node immediately.
586 resolve();
587
588 // Resolve all operands.
589 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000590 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000591 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000592 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000593
594 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000595 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000596 if (!N->isResolved())
597 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000598 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000599}
600
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000601static bool hasSelfReference(MDNode *N) {
602 for (Metadata *MD : N->operands())
603 if (MD == N)
604 return true;
605 return false;
606}
607
608MDNode *MDNode::replaceWithPermanentImpl() {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000609 switch (getMetadataID()) {
610 default:
611 // If this type isn't uniquable, replace with a distinct node.
612 return replaceWithDistinctImpl();
613
614#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
615 case CLASS##Kind: \
616 break;
617#include "llvm/IR/Metadata.def"
618 }
619
620 // Even if this type is uniquable, self-references have to be distinct.
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000621 if (hasSelfReference(this))
622 return replaceWithDistinctImpl();
623 return replaceWithUniquedImpl();
624}
625
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000626MDNode *MDNode::replaceWithUniquedImpl() {
627 // Try to uniquify in place.
628 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000629
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000630 if (UniquedNode == this) {
631 makeUniqued();
632 return this;
633 }
634
635 // Collision, so RAUW instead.
636 replaceAllUsesWith(UniquedNode);
637 deleteAsSubclass();
638 return UniquedNode;
639}
640
641MDNode *MDNode::replaceWithDistinctImpl() {
642 makeDistinct();
643 return this;
644}
645
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000646void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000647 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000648}
649
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000650void MDNode::dropAllReferences() {
651 for (unsigned I = 0, E = NumOperands; I != E; ++I)
652 setOperand(I, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000653 if (Context.hasReplaceableUses()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000654 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
655 (void)Context.takeReplaceableUses();
656 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000657}
658
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000659void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000660 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
661 assert(Op < getNumOperands() && "Expected valid operand");
662
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000663 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000664 // This node is not uniqued. Just set the operand and be done with it.
665 setOperand(Op, New);
666 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000667 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000668
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000669 // This node is uniqued.
670 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000671
672 Metadata *Old = getOperand(Op);
673 setOperand(Op, New);
674
Duncan P. N. Exon Smith9cbc69d2016-08-03 18:19:43 +0000675 // Drop uniquing for self-reference cycles and deleted constants.
676 if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000677 if (!isResolved())
678 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000679 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000680 return;
681 }
682
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000683 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000684 auto *Uniqued = uniquify();
685 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000686 if (!isResolved())
687 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000688 return;
689 }
690
691 // Collision.
692 if (!isResolved()) {
693 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000694 //
695 // First, clear out all operands to prevent any recursion (similar to
696 // dropAllReferences(), but we still need the use-list).
697 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
698 setOperand(O, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000699 if (Context.hasReplaceableUses())
700 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000701 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000702 return;
703 }
704
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000705 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000706 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000707}
708
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000709void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000710 switch (getMetadataID()) {
711 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000712 llvm_unreachable("Invalid subclass of MDNode");
713#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000714 case CLASS##Kind: \
715 delete cast<CLASS>(this); \
716 break;
717#include "llvm/IR/Metadata.def"
718 }
719}
720
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000721template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000722static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
723 if (T *U = getUniqued(Store, N))
724 return U;
725
726 Store.insert(N);
727 return N;
728}
729
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000730template <class NodeTy> struct MDNode::HasCachedHash {
731 typedef char Yes[1];
732 typedef char No[2];
733 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000734
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000735 template <class U>
736 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
737 template <class U> static No &check(...);
738
739 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
740};
741
742MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000743 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
744
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000745 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000746 switch (getMetadataID()) {
747 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000748 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
749#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000750 case CLASS##Kind: { \
751 CLASS *SubclassThis = cast<CLASS>(this); \
752 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
753 ShouldRecalculateHash; \
754 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
755 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
756 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000757#include "llvm/IR/Metadata.def"
758 }
759}
760
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000761void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000762 switch (getMetadataID()) {
763 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000764 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
765#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000766 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000767 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000768 break;
769#include "llvm/IR/Metadata.def"
770 }
771}
772
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000773MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000774 StorageType Storage, bool ShouldCreate) {
775 unsigned Hash = 0;
776 if (Storage == Uniqued) {
777 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000778 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
779 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000780 if (!ShouldCreate)
781 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000782 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000783 } else {
784 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
785 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000786
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000787 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
788 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000789}
790
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000791void MDNode::deleteTemporary(MDNode *N) {
792 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000793 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000794 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000795}
796
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000797void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000798 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
799 assert(!NumUnresolved && "Unexpected unresolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000800 Storage = Distinct;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000801 assert(isResolved() && "Expected this to be resolved");
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000802
803 // Reset the hash.
804 switch (getMetadataID()) {
805 default:
806 llvm_unreachable("Invalid subclass of MDNode");
807#define HANDLE_MDNODE_LEAF(CLASS) \
808 case CLASS##Kind: { \
809 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
810 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
811 break; \
812 }
813#include "llvm/IR/Metadata.def"
814 }
815
Duncan P. N. Exon Smith3eef9d12016-04-19 23:59:13 +0000816 getContext().pImpl->DistinctMDNodes.push_back(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000817}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000818
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000819void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
820 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000821 return;
Devang Patelf7188322009-09-03 01:39:20 +0000822
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000823 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000824 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000825 return;
826 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000827
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000828 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000829}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000830
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000831void MDNode::setOperand(unsigned I, Metadata *New) {
832 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000833 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000834}
835
Sanjay Patel9da9c762016-03-12 20:44:58 +0000836/// Get a node or a self-reference that looks like it.
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000837///
838/// Special handling for finding self-references, for use by \a
839/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
840/// when self-referencing nodes were still uniqued. If the first operand has
841/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000842static MDNode *getOrSelfReference(LLVMContext &Context,
843 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000844 if (!Ops.empty())
845 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
846 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
847 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
848 if (Ops[I] != N->getOperand(I))
849 return MDNode::get(Context, Ops);
850 return N;
851 }
852
853 return MDNode::get(Context, Ops);
854}
855
Hal Finkel94146652014-07-24 14:25:39 +0000856MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
857 if (!A)
858 return B;
859 if (!B)
860 return A;
861
David Majnemerfa0f1e62016-08-16 18:48:34 +0000862 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
863 MDs.insert(B->op_begin(), B->op_end());
Hal Finkel94146652014-07-24 14:25:39 +0000864
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000865 // FIXME: This preserves long-standing behaviour, but is it really the right
866 // behaviour? Or was that an unintended side-effect of node uniquing?
David Majnemerfa0f1e62016-08-16 18:48:34 +0000867 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
Hal Finkel94146652014-07-24 14:25:39 +0000868}
869
870MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
871 if (!A || !B)
872 return nullptr;
873
David Majnemer00940fb2016-08-16 18:48:37 +0000874 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
875 SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
876 MDs.remove_if([&](Metadata *MD) { return !is_contained(BSet, MD); });
Hal Finkel94146652014-07-24 14:25:39 +0000877
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000878 // FIXME: This preserves long-standing behaviour, but is it really the right
879 // behaviour? Or was that an unintended side-effect of node uniquing?
David Majnemer00940fb2016-08-16 18:48:37 +0000880 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
Hal Finkel94146652014-07-24 14:25:39 +0000881}
882
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000883MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
884 if (!A || !B)
885 return nullptr;
886
David Majnemerfa0f1e62016-08-16 18:48:34 +0000887 return concatenate(A, B);
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000888}
889
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000890MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
891 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000892 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000893
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000894 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
895 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000896 if (AVal.compare(BVal) == APFloat::cmpLessThan)
897 return A;
898 return B;
899}
900
901static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
902 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
903}
904
905static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
906 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
907}
908
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000909static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
910 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000911 ConstantRange NewRange(Low->getValue(), High->getValue());
912 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000913 APInt LB = EndPoints[Size - 2]->getValue();
914 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000915 ConstantRange LastRange(LB, LE);
916 if (canBeMerged(NewRange, LastRange)) {
917 ConstantRange Union = LastRange.unionWith(NewRange);
918 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000919 EndPoints[Size - 2] =
920 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
921 EndPoints[Size - 1] =
922 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000923 return true;
924 }
925 return false;
926}
927
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000928static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
929 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000930 if (!EndPoints.empty())
931 if (tryMergeRange(EndPoints, Low, High))
932 return;
933
934 EndPoints.push_back(Low);
935 EndPoints.push_back(High);
936}
937
938MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
939 // Given two ranges, we want to compute the union of the ranges. This
940 // is slightly complitade by having to combine the intervals and merge
941 // the ones that overlap.
942
943 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000944 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000945
946 if (A == B)
947 return A;
948
949 // First, walk both lists in older of the lower boundary of each interval.
950 // 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 +0000951 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000952 int AI = 0;
953 int BI = 0;
954 int AN = A->getNumOperands() / 2;
955 int BN = B->getNumOperands() / 2;
956 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000957 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
958 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000959
960 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000961 addRange(EndPoints, ALow,
962 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000963 ++AI;
964 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000965 addRange(EndPoints, BLow,
966 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000967 ++BI;
968 }
969 }
970 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000971 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
972 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000973 ++AI;
974 }
975 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000976 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
977 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000978 ++BI;
979 }
980
981 // If we have more than 2 ranges (4 endpoints) we have to try to merge
982 // the last and first ones.
983 unsigned Size = EndPoints.size();
984 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000985 ConstantInt *FB = EndPoints[0];
986 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000987 if (tryMergeRange(EndPoints, FB, FE)) {
988 for (unsigned i = 0; i < Size - 2; ++i) {
989 EndPoints[i] = EndPoints[i + 2];
990 }
991 EndPoints.resize(Size - 2);
992 }
993 }
994
995 // If in the end we have a single range, it is possible that it is now the
996 // full range. Just drop the metadata in that case.
997 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000998 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000999 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +00001000 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001001 }
1002
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001003 SmallVector<Metadata *, 4> MDs;
1004 MDs.reserve(EndPoints.size());
1005 for (auto *I : EndPoints)
1006 MDs.push_back(ConstantAsMetadata::get(I));
1007 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001008}
1009
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001010MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1011 if (!A || !B)
1012 return nullptr;
1013
1014 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1015 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1016 if (AVal->getZExtValue() < BVal->getZExtValue())
1017 return A;
1018 return B;
1019}
1020
Devang Patel05a26fb2009-07-29 00:33:07 +00001021//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +00001022// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +00001023//
Devang Patel943ddf62010-01-12 18:34:06 +00001024
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001025static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1026 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +00001027}
1028
Dan Gohman2637cc12010-07-21 23:38:33 +00001029NamedMDNode::NamedMDNode(const Twine &N)
Duncan P. N. Exon Smithc5754a62014-11-05 18:16:03 +00001030 : Name(N.str()), Parent(nullptr),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001031 Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +00001032
Chris Lattner1bc810b2009-12-28 08:07:14 +00001033NamedMDNode::~NamedMDNode() {
1034 dropAllReferences();
1035 delete &getNMDOps(Operands);
1036}
1037
Chris Lattner9b493022009-12-31 01:22:29 +00001038unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001039 return (unsigned)getNMDOps(Operands).size();
1040}
1041
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001042MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +00001043 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001044 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001045 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +00001046}
1047
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001048void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +00001049
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001050void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1051 assert(I < getNumOperands() && "Invalid operand number");
1052 getNMDOps(Operands)[I].reset(New);
1053}
1054
Dehao Chene0e0ed12016-09-16 18:27:20 +00001055void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
Devang Patel79238d72009-08-03 06:19:01 +00001056
Dehao Chene0e0ed12016-09-16 18:27:20 +00001057void NamedMDNode::dropAllReferences() { getNMDOps(Operands).clear(); }
Devang Patel79238d72009-08-03 06:19:01 +00001058
Dehao Chene0e0ed12016-09-16 18:27:20 +00001059StringRef NamedMDNode::getName() const { return StringRef(Name); }
Devang Pateld5497a4b2009-09-16 18:09:00 +00001060
1061//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001062// Instruction Metadata method implementations.
1063//
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001064void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1065 for (auto &I : Attachments)
1066 if (I.first == ID) {
1067 I.second.reset(&MD);
1068 return;
1069 }
1070 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1071 std::make_tuple(&MD));
1072}
1073
1074void MDAttachmentMap::erase(unsigned ID) {
1075 if (empty())
1076 return;
1077
1078 // Common case is one/last value.
1079 if (Attachments.back().first == ID) {
1080 Attachments.pop_back();
1081 return;
1082 }
1083
1084 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1085 ++I)
1086 if (I->first == ID) {
1087 *I = std::move(Attachments.back());
1088 Attachments.pop_back();
1089 return;
1090 }
1091}
1092
1093MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1094 for (const auto &I : Attachments)
1095 if (I.first == ID)
1096 return I.second;
1097 return nullptr;
1098}
1099
1100void MDAttachmentMap::getAll(
1101 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1102 Result.append(Attachments.begin(), Attachments.end());
1103
1104 // Sort the resulting array so it is stable.
1105 if (Result.size() > 1)
1106 array_pod_sort(Result.begin(), Result.end());
1107}
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001108
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001109void MDGlobalAttachmentMap::insert(unsigned ID, MDNode &MD) {
1110 Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1111}
1112
1113void MDGlobalAttachmentMap::get(unsigned ID,
1114 SmallVectorImpl<MDNode *> &Result) {
1115 for (auto A : Attachments)
1116 if (A.MDKind == ID)
1117 Result.push_back(A.Node);
1118}
1119
1120void MDGlobalAttachmentMap::erase(unsigned ID) {
1121 auto Follower = Attachments.begin();
1122 for (auto Leader = Attachments.begin(), E = Attachments.end(); Leader != E;
1123 ++Leader) {
1124 if (Leader->MDKind != ID) {
1125 if (Follower != Leader)
1126 *Follower = std::move(*Leader);
1127 ++Follower;
1128 }
1129 }
1130 Attachments.resize(Follower - Attachments.begin());
1131}
1132
1133void MDGlobalAttachmentMap::getAll(
1134 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1135 for (auto &A : Attachments)
1136 Result.emplace_back(A.MDKind, A.Node);
1137
1138 // Sort the resulting array so it is stable with respect to metadata IDs. We
1139 // need to preserve the original insertion order though.
1140 std::stable_sort(
1141 Result.begin(), Result.end(),
1142 [](const std::pair<unsigned, MDNode *> &A,
1143 const std::pair<unsigned, MDNode *> &B) { return A.first < B.first; });
1144}
1145
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001146void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1147 if (!Node && !hasMetadata())
1148 return;
1149 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001150}
1151
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001152MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +00001153 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001154}
1155
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001156void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001157 if (!hasMetadataHashEntry())
1158 return; // Nothing to remove!
1159
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001160 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
Rafael Espindolaab73c492014-01-28 16:56:46 +00001161
Aditya Kumar0a48b372016-09-26 21:01:13 +00001162 SmallSet<unsigned, 4> KnownSet;
1163 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
Rafael Espindolaab73c492014-01-28 16:56:46 +00001164 if (KnownSet.empty()) {
1165 // Just drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001166 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001167 setHasMetadataHashEntry(false);
1168 return;
1169 }
1170
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001171 auto &Info = InstructionMetadata[this];
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001172 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1173 return !KnownSet.count(I.first);
1174 });
Rafael Espindolaab73c492014-01-28 16:56:46 +00001175
Duncan P. N. Exon Smith75ef0c02015-04-24 20:23:44 +00001176 if (Info.empty()) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001177 // Drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001178 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001179 setHasMetadataHashEntry(false);
1180 }
1181}
1182
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001183void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1184 if (!Node && !hasMetadata())
1185 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001186
Chris Lattnerc263b422010-03-30 23:03:27 +00001187 // Handle 'dbg' as a special case since it is not stored in the hash table.
1188 if (KindID == LLVMContext::MD_dbg) {
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001189 DbgLoc = DebugLoc(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001190 return;
1191 }
Dehao Chene0e0ed12016-09-16 18:27:20 +00001192
Chris Lattnera0566972009-12-29 09:01:33 +00001193 // Handle the case when we're adding/updating metadata on an instruction.
1194 if (Node) {
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001195 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001196 assert(!Info.empty() == hasMetadataHashEntry() &&
1197 "HasMetadata bit is wonked");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001198 if (Info.empty())
Chris Lattnerc263b422010-03-30 23:03:27 +00001199 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001200 Info.set(KindID, *Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001201 return;
1202 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001203
Chris Lattnera0566972009-12-29 09:01:33 +00001204 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001205 assert((hasMetadataHashEntry() ==
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001206 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001207 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001208 if (!hasMetadataHashEntry())
Dehao Chene0e0ed12016-09-16 18:27:20 +00001209 return; // Nothing to remove!
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001210 auto &Info = getContext().pImpl->InstructionMetadata[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001211
Chris Lattnerc263b422010-03-30 23:03:27 +00001212 // Handle removal of an existing value.
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001213 Info.erase(KindID);
1214
1215 if (!Info.empty())
1216 return;
1217
1218 getContext().pImpl->InstructionMetadata.erase(this);
1219 setHasMetadataHashEntry(false);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001220}
1221
Hal Finkelcc39b672014-07-24 12:16:19 +00001222void Instruction::setAAMetadata(const AAMDNodes &N) {
1223 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001224 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1225 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001226}
1227
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001228MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001229 // Handle 'dbg' as a special case since it is not stored in the hash table.
1230 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001231 return DbgLoc.getAsMDNode();
1232
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001233 if (!hasMetadataHashEntry())
1234 return nullptr;
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001235 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001236 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001237
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001238 return Info.lookup(KindID);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001239}
1240
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001241void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001242 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001243 Result.clear();
Dehao Chene0e0ed12016-09-16 18:27:20 +00001244
Chris Lattnerc263b422010-03-30 23:03:27 +00001245 // 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 +00001246 if (DbgLoc) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001247 Result.push_back(
1248 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Dehao Chene0e0ed12016-09-16 18:27:20 +00001249 if (!hasMetadataHashEntry())
1250 return;
Chris Lattnerc263b422010-03-30 23:03:27 +00001251 }
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001252
Chris Lattnerc263b422010-03-30 23:03:27 +00001253 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001254 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001255 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001256 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnera0566972009-12-29 09:01:33 +00001257 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001258 Info.getAll(Result);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001259}
1260
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001261void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001262 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001263 Result.clear();
1264 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001265 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001266 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001267 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001268 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001269 Info.getAll(Result);
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001270}
1271
Dehao Chene0e0ed12016-09-16 18:27:20 +00001272bool Instruction::extractProfMetadata(uint64_t &TrueVal,
1273 uint64_t &FalseVal) const {
1274 assert(
1275 (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
1276 "Looking for branch weights on something besides branch or select");
Sanjay Pateld66607b2016-04-26 17:11:17 +00001277
1278 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1279 if (!ProfileData || ProfileData->getNumOperands() != 3)
1280 return false;
1281
1282 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1283 if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1284 return false;
1285
1286 auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
1287 auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
1288 if (!CITrue || !CIFalse)
1289 return false;
1290
1291 TrueVal = CITrue->getValue().getZExtValue();
1292 FalseVal = CIFalse->getValue().getZExtValue();
1293
1294 return true;
1295}
1296
Dehao Chene0e0ed12016-09-16 18:27:20 +00001297bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
Dehao Chen9232f982016-07-11 16:48:54 +00001298 assert((getOpcode() == Instruction::Br ||
1299 getOpcode() == Instruction::Select ||
Dehao Chen71021cd2016-07-11 17:36:02 +00001300 getOpcode() == Instruction::Call ||
1301 getOpcode() == Instruction::Invoke) &&
Dehao Chen9232f982016-07-11 16:48:54 +00001302 "Looking for branch weights on something besides branch");
1303
1304 TotalVal = 0;
1305 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1306 if (!ProfileData)
1307 return false;
1308
1309 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1310 if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1311 return false;
1312
1313 TotalVal = 0;
David Majnemerdd8f6bd2016-07-11 17:09:06 +00001314 for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
Dehao Chen9232f982016-07-11 16:48:54 +00001315 auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
1316 if (!V)
1317 return false;
1318 TotalVal += V->getValue().getZExtValue();
1319 }
1320 return true;
1321}
1322
Dan Gohman48a995f2010-07-20 22:25:04 +00001323void Instruction::clearMetadataHashEntries() {
1324 assert(hasMetadataHashEntry() && "Caller should check");
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001325 getContext().pImpl->InstructionMetadata.erase(this);
Dan Gohman48a995f2010-07-20 22:25:04 +00001326 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001327}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001328
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001329void GlobalObject::getMetadata(unsigned KindID,
1330 SmallVectorImpl<MDNode *> &MDs) const {
1331 if (hasMetadata())
1332 getContext().pImpl->GlobalObjectMetadata[this].get(KindID, MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001333}
1334
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001335void GlobalObject::getMetadata(StringRef Kind,
1336 SmallVectorImpl<MDNode *> &MDs) const {
1337 if (hasMetadata())
1338 getMetadata(getContext().getMDKindID(Kind), MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001339}
1340
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001341void GlobalObject::addMetadata(unsigned KindID, MDNode &MD) {
1342 if (!hasMetadata())
1343 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001344
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001345 getContext().pImpl->GlobalObjectMetadata[this].insert(KindID, MD);
1346}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001347
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001348void GlobalObject::addMetadata(StringRef Kind, MDNode &MD) {
1349 addMetadata(getContext().getMDKindID(Kind), MD);
1350}
1351
1352void GlobalObject::eraseMetadata(unsigned KindID) {
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001353 // Nothing to unset.
1354 if (!hasMetadata())
1355 return;
1356
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001357 auto &Store = getContext().pImpl->GlobalObjectMetadata[this];
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001358 Store.erase(KindID);
1359 if (Store.empty())
1360 clearMetadata();
1361}
1362
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001363void GlobalObject::getAllMetadata(
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001364 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1365 MDs.clear();
1366
1367 if (!hasMetadata())
1368 return;
1369
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001370 getContext().pImpl->GlobalObjectMetadata[this].getAll(MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001371}
1372
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001373void GlobalObject::clearMetadata() {
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001374 if (!hasMetadata())
1375 return;
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001376 getContext().pImpl->GlobalObjectMetadata.erase(this);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001377 setHasMetadataHashEntry(false);
1378}
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001379
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001380void GlobalObject::setMetadata(unsigned KindID, MDNode *N) {
1381 eraseMetadata(KindID);
1382 if (N)
1383 addMetadata(KindID, *N);
1384}
1385
1386void GlobalObject::setMetadata(StringRef Kind, MDNode *N) {
1387 setMetadata(getContext().getMDKindID(Kind), N);
1388}
1389
1390MDNode *GlobalObject::getMetadata(unsigned KindID) const {
1391 SmallVector<MDNode *, 1> MDs;
1392 getMetadata(KindID, MDs);
1393 assert(MDs.size() <= 1 && "Expected at most one metadata attachment");
1394 if (MDs.empty())
1395 return nullptr;
1396 return MDs[0];
1397}
1398
1399MDNode *GlobalObject::getMetadata(StringRef Kind) const {
1400 return getMetadata(getContext().getMDKindID(Kind));
1401}
1402
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001403void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +00001404 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1405 Other->getAllMetadata(MDs);
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001406 for (auto &MD : MDs) {
1407 // We need to adjust the type metadata offset.
1408 if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1409 auto *OffsetConst = cast<ConstantInt>(
1410 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1411 Metadata *TypeId = MD.second->getOperand(1);
1412 auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1413 OffsetConst->getType(), OffsetConst->getValue() + Offset));
1414 addMetadata(LLVMContext::MD_type,
1415 *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1416 continue;
1417 }
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001418 // If an offset adjustment was specified we need to modify the DIExpression
1419 // to prepend the adjustment:
1420 // !DIExpression(DW_OP_plus, Offset, [original expr])
1421 if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
1422 DIGlobalVariable *GV = cast<DIGlobalVariable>(MD.second);
1423 DIExpression *E = GV->getExpr();
1424 ArrayRef<uint64_t> OrigElements;
1425 if (E)
1426 OrigElements = E->getElements();
1427 std::vector<uint64_t> Elements(OrigElements.size() + 2);
1428 Elements[0] = dwarf::DW_OP_plus;
1429 Elements[1] = Offset;
1430 std::copy(OrigElements.begin(), OrigElements.end(), Elements.begin() + 2);
1431 GV->replaceExpr(DIExpression::get(getContext(), Elements));
1432 }
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +00001433 addMetadata(MD.first, *MD.second);
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001434 }
1435}
1436
1437void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
1438 addMetadata(
1439 LLVMContext::MD_type,
1440 *MDTuple::get(getContext(),
1441 {llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1442 Type::getInt64Ty(getContext()), Offset)),
1443 TypeID}));
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +00001444}
1445
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001446void Function::setSubprogram(DISubprogram *SP) {
1447 setMetadata(LLVMContext::MD_dbg, SP);
1448}
1449
1450DISubprogram *Function::getSubprogram() const {
1451 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1452}
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001453
1454void GlobalVariable::addDebugInfo(DIGlobalVariable *GV) {
1455 addMetadata(LLVMContext::MD_dbg, *GV);
1456}
1457
1458void GlobalVariable::getDebugInfo(
1459 SmallVectorImpl<DIGlobalVariable *> &GVs) const {
1460 SmallVector<MDNode *, 1> MDs;
1461 getMetadata(LLVMContext::MD_dbg, MDs);
1462 for (MDNode *MD : MDs)
1463 GVs.push_back(cast<DIGlobalVariable>(MD));
1464}