blob: ad95bff9e83d146ce33325c605976e07fb341061 [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");
Owen Anderson7349ab92015-06-01 22:24:01 +0000317 assert(!V->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000318 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000319 V->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000320 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000321 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000322 else
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000323 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000324 }
325
326 return Entry;
327}
328
329ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
330 assert(V && "Unexpected null Value");
331 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
332}
333
334void ValueAsMetadata::handleDeletion(Value *V) {
335 assert(V && "Expected valid value");
336
337 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
338 auto I = Store.find(V);
339 if (I == Store.end())
340 return;
341
342 // Remove old entry from the map.
343 ValueAsMetadata *MD = I->second;
344 assert(MD && "Expected valid metadata");
345 assert(MD->getValue() == V && "Expected valid mapping");
346 Store.erase(I);
347
348 // Delete the metadata.
349 MD->replaceAllUsesWith(nullptr);
350 delete MD;
351}
352
353void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
354 assert(From && "Expected valid value");
355 assert(To && "Expected valid value");
356 assert(From != To && "Expected changed value");
357 assert(From->getType() == To->getType() && "Unexpected type change");
358
359 LLVMContext &Context = From->getType()->getContext();
360 auto &Store = Context.pImpl->ValuesAsMetadata;
361 auto I = Store.find(From);
362 if (I == Store.end()) {
Owen Anderson7349ab92015-06-01 22:24:01 +0000363 assert(!From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000364 "Expected From not to be used by metadata");
365 return;
366 }
367
368 // Remove old entry from the map.
Owen Anderson7349ab92015-06-01 22:24:01 +0000369 assert(From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000370 "Expected From to be used by metadata");
Owen Anderson7349ab92015-06-01 22:24:01 +0000371 From->IsUsedByMD = false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000372 ValueAsMetadata *MD = I->second;
373 assert(MD && "Expected valid metadata");
374 assert(MD->getValue() == From && "Expected valid mapping");
375 Store.erase(I);
376
377 if (isa<LocalAsMetadata>(MD)) {
378 if (auto *C = dyn_cast<Constant>(To)) {
379 // Local became a constant.
380 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
381 delete MD;
382 return;
383 }
384 if (getLocalFunction(From) && getLocalFunction(To) &&
385 getLocalFunction(From) != getLocalFunction(To)) {
386 // Function changed.
387 MD->replaceAllUsesWith(nullptr);
388 delete MD;
389 return;
390 }
391 } else if (!isa<Constant>(To)) {
392 // Changed to function-local value.
393 MD->replaceAllUsesWith(nullptr);
394 delete MD;
395 return;
396 }
397
398 auto *&Entry = Store[To];
399 if (Entry) {
400 // The target already exists.
401 MD->replaceAllUsesWith(Entry);
402 delete MD;
403 return;
404 }
405
406 // Update MD in place (and update the map entry).
Owen Anderson7349ab92015-06-01 22:24:01 +0000407 assert(!To->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000408 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000409 To->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000410 MD->V = To;
411 Entry = MD;
412}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000413
Devang Patela4f43fb2009-07-28 21:49:47 +0000414//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000415// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000416//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000417
Devang Pateldcb99d32009-10-22 00:10:15 +0000418MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000419 auto &Store = Context.pImpl->MDStringCache;
Benjamin Kramereab3d362016-07-21 13:37:48 +0000420 auto I = Store.try_emplace(Str);
Mehdi Aminicb708b22016-03-25 05:58:04 +0000421 auto &MapEntry = I.first->getValue();
422 if (!I.second)
423 return &MapEntry;
424 MapEntry.Entry = &*I.first;
425 return &MapEntry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000426}
427
428StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000429 assert(Entry && "Expected to find string map entry");
430 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000431}
432
433//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000434// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000435//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000436
James Y Knight8096d342015-06-17 01:21:20 +0000437// Assert that the MDNode types will not be unaligned by the objects
438// prepended to them.
439#define HANDLE_MDNODE_LEAF(CLASS) \
James Y Knightf27e4412015-06-17 13:53:12 +0000440 static_assert( \
441 llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
442 "Alignment is insufficient after objects prepended to " #CLASS);
James Y Knight8096d342015-06-17 01:21:20 +0000443#include "llvm/IR/Metadata.def"
444
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000445void *MDNode::operator new(size_t Size, unsigned NumOps) {
James Y Knight8096d342015-06-17 01:21:20 +0000446 size_t OpSize = NumOps * sizeof(MDOperand);
447 // uint64_t is the most aligned type we need support (ensured by static_assert
448 // above)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000449 OpSize = alignTo(OpSize, llvm::alignOf<uint64_t>());
James Y Knight8096d342015-06-17 01:21:20 +0000450 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000451 MDOperand *O = static_cast<MDOperand *>(Ptr);
James Y Knight8096d342015-06-17 01:21:20 +0000452 for (MDOperand *E = O - NumOps; O != E; --O)
453 (void)new (O - 1) MDOperand;
454 return Ptr;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000455}
456
Naomi Musgrave21c1bc42015-08-31 21:06:08 +0000457void MDNode::operator delete(void *Mem) {
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000458 MDNode *N = static_cast<MDNode *>(Mem);
James Y Knight8096d342015-06-17 01:21:20 +0000459 size_t OpSize = N->NumOperands * sizeof(MDOperand);
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000460 OpSize = alignTo(OpSize, llvm::alignOf<uint64_t>());
James Y Knight8096d342015-06-17 01:21:20 +0000461
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000462 MDOperand *O = static_cast<MDOperand *>(Mem);
463 for (MDOperand *E = O - N->NumOperands; O != E; --O)
464 (O - 1)->~MDOperand();
James Y Knight8096d342015-06-17 01:21:20 +0000465 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000466}
467
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000468MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000469 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
470 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
471 NumUnresolved(0), Context(Context) {
472 unsigned Op = 0;
473 for (Metadata *MD : Ops1)
474 setOperand(Op++, MD);
475 for (Metadata *MD : Ops2)
476 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000477
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000478 if (!isUniqued())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000479 return;
480
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000481 // Count the unresolved operands. If there are any, RAUW support will be
482 // added lazily on first reference.
483 countUnresolvedOperands();
Devang Patela4f43fb2009-07-28 21:49:47 +0000484}
485
Duncan P. N. Exon Smith03e05832015-01-20 02:56:57 +0000486TempMDNode MDNode::clone() const {
487 switch (getMetadataID()) {
488 default:
489 llvm_unreachable("Invalid MDNode subclass");
490#define HANDLE_MDNODE_LEAF(CLASS) \
491 case CLASS##Kind: \
492 return cast<CLASS>(this)->cloneImpl();
493#include "llvm/IR/Metadata.def"
494 }
495}
496
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000497static bool isOperandUnresolved(Metadata *Op) {
498 if (auto *N = dyn_cast_or_null<MDNode>(Op))
499 return !N->isResolved();
500 return false;
501}
502
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000503void MDNode::countUnresolvedOperands() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000504 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000505 assert(isUniqued() && "Expected this to be uniqued");
Sanjoy Das39c226f2016-06-10 21:18:39 +0000506 NumUnresolved = count_if(operands(), isOperandUnresolved);
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000507}
508
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000509void MDNode::makeUniqued() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000510 assert(isTemporary() && "Expected this to be temporary");
511 assert(!isResolved() && "Expected this to be unresolved");
512
Duncan P. N. Exon Smithcb33d6f2015-03-31 20:50:50 +0000513 // Enable uniquing callbacks.
514 for (auto &Op : mutable_operands())
515 Op.reset(Op.get(), this);
516
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000517 // Make this 'uniqued'.
518 Storage = Uniqued;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000519 countUnresolvedOperands();
520 if (!NumUnresolved) {
521 dropReplaceableUses();
522 assert(isResolved() && "Expected this to be resolved");
523 }
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000524
525 assert(isUniqued() && "Expected this to be uniqued");
526}
527
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000528void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000529 assert(isTemporary() && "Expected this to be temporary");
530 assert(!isResolved() && "Expected this to be unresolved");
531
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000532 // Drop RAUW support and store as a distinct node.
533 dropReplaceableUses();
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000534 storeDistinctInContext();
535
536 assert(isDistinct() && "Expected this to be distinct");
537 assert(isResolved() && "Expected this to be resolved");
538}
539
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000540void MDNode::resolve() {
Duncan P. N. Exon Smithb8f79602015-01-19 19:26:24 +0000541 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000542 assert(!isResolved() && "Expected this to be unresolved");
543
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000544 NumUnresolved = 0;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000545 dropReplaceableUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000546
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000547 assert(isResolved() && "Expected this to be resolved");
548}
549
550void MDNode::dropReplaceableUses() {
551 assert(!NumUnresolved && "Unexpected unresolved operand");
552
553 // Drop any RAUW support.
554 if (Context.hasReplaceableUses())
555 Context.takeReplaceableUses()->resolveAllUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000556}
557
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000558void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000559 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000560 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000561
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000562 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000563 if (!isOperandUnresolved(Old)) {
564 if (isOperandUnresolved(New))
565 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000566 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000567 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000568 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000569}
570
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000571void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000572 assert(!isResolved() && "Expected this to be unresolved");
573 if (isTemporary())
574 return;
575
576 assert(isUniqued() && "Expected this to be uniqued");
577 if (--NumUnresolved)
578 return;
579
580 // Last unresolved operand has just been resolved.
581 dropReplaceableUses();
582 assert(isResolved() && "Expected this to become resolved");
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000583}
584
Teresa Johnsonb703c772016-03-29 18:24:19 +0000585void MDNode::resolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000586 if (isResolved())
587 return;
588
589 // Resolve this node immediately.
590 resolve();
591
592 // Resolve all operands.
593 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000594 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000595 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000596 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000597
598 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000599 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000600 if (!N->isResolved())
601 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000602 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000603}
604
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000605static bool hasSelfReference(MDNode *N) {
606 for (Metadata *MD : N->operands())
607 if (MD == N)
608 return true;
609 return false;
610}
611
612MDNode *MDNode::replaceWithPermanentImpl() {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000613 switch (getMetadataID()) {
614 default:
615 // If this type isn't uniquable, replace with a distinct node.
616 return replaceWithDistinctImpl();
617
618#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
619 case CLASS##Kind: \
620 break;
621#include "llvm/IR/Metadata.def"
622 }
623
624 // Even if this type is uniquable, self-references have to be distinct.
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000625 if (hasSelfReference(this))
626 return replaceWithDistinctImpl();
627 return replaceWithUniquedImpl();
628}
629
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000630MDNode *MDNode::replaceWithUniquedImpl() {
631 // Try to uniquify in place.
632 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000633
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000634 if (UniquedNode == this) {
635 makeUniqued();
636 return this;
637 }
638
639 // Collision, so RAUW instead.
640 replaceAllUsesWith(UniquedNode);
641 deleteAsSubclass();
642 return UniquedNode;
643}
644
645MDNode *MDNode::replaceWithDistinctImpl() {
646 makeDistinct();
647 return this;
648}
649
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000650void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000651 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000652}
653
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000654void MDNode::dropAllReferences() {
655 for (unsigned I = 0, E = NumOperands; I != E; ++I)
656 setOperand(I, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000657 if (Context.hasReplaceableUses()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000658 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
659 (void)Context.takeReplaceableUses();
660 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000661}
662
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000663void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000664 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
665 assert(Op < getNumOperands() && "Expected valid operand");
666
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000667 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000668 // This node is not uniqued. Just set the operand and be done with it.
669 setOperand(Op, New);
670 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000671 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000672
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000673 // This node is uniqued.
674 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000675
676 Metadata *Old = getOperand(Op);
677 setOperand(Op, New);
678
Duncan P. N. Exon Smith9cbc69d2016-08-03 18:19:43 +0000679 // Drop uniquing for self-reference cycles and deleted constants.
680 if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000681 if (!isResolved())
682 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000683 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000684 return;
685 }
686
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000687 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000688 auto *Uniqued = uniquify();
689 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000690 if (!isResolved())
691 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000692 return;
693 }
694
695 // Collision.
696 if (!isResolved()) {
697 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000698 //
699 // First, clear out all operands to prevent any recursion (similar to
700 // dropAllReferences(), but we still need the use-list).
701 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
702 setOperand(O, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000703 if (Context.hasReplaceableUses())
704 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000705 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000706 return;
707 }
708
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000709 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000710 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000711}
712
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000713void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000714 switch (getMetadataID()) {
715 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000716 llvm_unreachable("Invalid subclass of MDNode");
717#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000718 case CLASS##Kind: \
719 delete cast<CLASS>(this); \
720 break;
721#include "llvm/IR/Metadata.def"
722 }
723}
724
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000725template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000726static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
727 if (T *U = getUniqued(Store, N))
728 return U;
729
730 Store.insert(N);
731 return N;
732}
733
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000734template <class NodeTy> struct MDNode::HasCachedHash {
735 typedef char Yes[1];
736 typedef char No[2];
737 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000738
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000739 template <class U>
740 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
741 template <class U> static No &check(...);
742
743 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
744};
745
746MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000747 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
748
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000749 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000750 switch (getMetadataID()) {
751 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000752 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
753#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000754 case CLASS##Kind: { \
755 CLASS *SubclassThis = cast<CLASS>(this); \
756 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
757 ShouldRecalculateHash; \
758 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
759 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
760 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000761#include "llvm/IR/Metadata.def"
762 }
763}
764
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000765void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000766 switch (getMetadataID()) {
767 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000768 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
769#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000770 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000771 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000772 break;
773#include "llvm/IR/Metadata.def"
774 }
775}
776
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000777MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000778 StorageType Storage, bool ShouldCreate) {
779 unsigned Hash = 0;
780 if (Storage == Uniqued) {
781 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000782 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
783 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000784 if (!ShouldCreate)
785 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000786 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000787 } else {
788 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
789 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000790
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000791 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
792 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000793}
794
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000795void MDNode::deleteTemporary(MDNode *N) {
796 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000797 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000798 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000799}
800
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000801void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000802 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
803 assert(!NumUnresolved && "Unexpected unresolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000804 Storage = Distinct;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000805 assert(isResolved() && "Expected this to be resolved");
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000806
807 // Reset the hash.
808 switch (getMetadataID()) {
809 default:
810 llvm_unreachable("Invalid subclass of MDNode");
811#define HANDLE_MDNODE_LEAF(CLASS) \
812 case CLASS##Kind: { \
813 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
814 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
815 break; \
816 }
817#include "llvm/IR/Metadata.def"
818 }
819
Duncan P. N. Exon Smith3eef9d12016-04-19 23:59:13 +0000820 getContext().pImpl->DistinctMDNodes.push_back(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000821}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000822
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000823void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
824 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000825 return;
Devang Patelf7188322009-09-03 01:39:20 +0000826
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000827 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000828 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000829 return;
830 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000831
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000832 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000833}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000834
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000835void MDNode::setOperand(unsigned I, Metadata *New) {
836 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000837 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000838}
839
Sanjay Patel9da9c762016-03-12 20:44:58 +0000840/// Get a node or a self-reference that looks like it.
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000841///
842/// Special handling for finding self-references, for use by \a
843/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
844/// when self-referencing nodes were still uniqued. If the first operand has
845/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000846static MDNode *getOrSelfReference(LLVMContext &Context,
847 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000848 if (!Ops.empty())
849 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
850 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
851 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
852 if (Ops[I] != N->getOperand(I))
853 return MDNode::get(Context, Ops);
854 return N;
855 }
856
857 return MDNode::get(Context, Ops);
858}
859
Hal Finkel94146652014-07-24 14:25:39 +0000860MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
861 if (!A)
862 return B;
863 if (!B)
864 return A;
865
David Majnemerfa0f1e62016-08-16 18:48:34 +0000866 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
867 MDs.insert(B->op_begin(), B->op_end());
Hal Finkel94146652014-07-24 14:25:39 +0000868
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000869 // FIXME: This preserves long-standing behaviour, but is it really the right
870 // behaviour? Or was that an unintended side-effect of node uniquing?
David Majnemerfa0f1e62016-08-16 18:48:34 +0000871 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
Hal Finkel94146652014-07-24 14:25:39 +0000872}
873
874MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
875 if (!A || !B)
876 return nullptr;
877
David Majnemer00940fb2016-08-16 18:48:37 +0000878 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
879 SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
880 MDs.remove_if([&](Metadata *MD) { return !is_contained(BSet, MD); });
Hal Finkel94146652014-07-24 14:25:39 +0000881
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000882 // FIXME: This preserves long-standing behaviour, but is it really the right
883 // behaviour? Or was that an unintended side-effect of node uniquing?
David Majnemer00940fb2016-08-16 18:48:37 +0000884 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
Hal Finkel94146652014-07-24 14:25:39 +0000885}
886
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000887MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
888 if (!A || !B)
889 return nullptr;
890
David Majnemerfa0f1e62016-08-16 18:48:34 +0000891 return concatenate(A, B);
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000892}
893
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000894MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
895 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000896 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000897
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000898 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
899 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000900 if (AVal.compare(BVal) == APFloat::cmpLessThan)
901 return A;
902 return B;
903}
904
905static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
906 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
907}
908
909static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
910 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
911}
912
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000913static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
914 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000915 ConstantRange NewRange(Low->getValue(), High->getValue());
916 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000917 APInt LB = EndPoints[Size - 2]->getValue();
918 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000919 ConstantRange LastRange(LB, LE);
920 if (canBeMerged(NewRange, LastRange)) {
921 ConstantRange Union = LastRange.unionWith(NewRange);
922 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000923 EndPoints[Size - 2] =
924 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
925 EndPoints[Size - 1] =
926 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000927 return true;
928 }
929 return false;
930}
931
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000932static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
933 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000934 if (!EndPoints.empty())
935 if (tryMergeRange(EndPoints, Low, High))
936 return;
937
938 EndPoints.push_back(Low);
939 EndPoints.push_back(High);
940}
941
942MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
943 // Given two ranges, we want to compute the union of the ranges. This
944 // is slightly complitade by having to combine the intervals and merge
945 // the ones that overlap.
946
947 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000948 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000949
950 if (A == B)
951 return A;
952
953 // First, walk both lists in older of the lower boundary of each interval.
954 // 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 +0000955 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000956 int AI = 0;
957 int BI = 0;
958 int AN = A->getNumOperands() / 2;
959 int BN = B->getNumOperands() / 2;
960 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000961 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
962 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000963
964 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000965 addRange(EndPoints, ALow,
966 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000967 ++AI;
968 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000969 addRange(EndPoints, BLow,
970 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000971 ++BI;
972 }
973 }
974 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000975 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
976 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000977 ++AI;
978 }
979 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000980 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
981 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000982 ++BI;
983 }
984
985 // If we have more than 2 ranges (4 endpoints) we have to try to merge
986 // the last and first ones.
987 unsigned Size = EndPoints.size();
988 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000989 ConstantInt *FB = EndPoints[0];
990 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000991 if (tryMergeRange(EndPoints, FB, FE)) {
992 for (unsigned i = 0; i < Size - 2; ++i) {
993 EndPoints[i] = EndPoints[i + 2];
994 }
995 EndPoints.resize(Size - 2);
996 }
997 }
998
999 // If in the end we have a single range, it is possible that it is now the
1000 // full range. Just drop the metadata in that case.
1001 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001002 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001003 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +00001004 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001005 }
1006
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001007 SmallVector<Metadata *, 4> MDs;
1008 MDs.reserve(EndPoints.size());
1009 for (auto *I : EndPoints)
1010 MDs.push_back(ConstantAsMetadata::get(I));
1011 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001012}
1013
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001014MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1015 if (!A || !B)
1016 return nullptr;
1017
1018 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1019 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1020 if (AVal->getZExtValue() < BVal->getZExtValue())
1021 return A;
1022 return B;
1023}
1024
Devang Patel05a26fb2009-07-29 00:33:07 +00001025//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +00001026// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +00001027//
Devang Patel943ddf62010-01-12 18:34:06 +00001028
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001029static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1030 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +00001031}
1032
Dan Gohman2637cc12010-07-21 23:38:33 +00001033NamedMDNode::NamedMDNode(const Twine &N)
Duncan P. N. Exon Smithc5754a62014-11-05 18:16:03 +00001034 : Name(N.str()), Parent(nullptr),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001035 Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +00001036
Chris Lattner1bc810b2009-12-28 08:07:14 +00001037NamedMDNode::~NamedMDNode() {
1038 dropAllReferences();
1039 delete &getNMDOps(Operands);
1040}
1041
Chris Lattner9b493022009-12-31 01:22:29 +00001042unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001043 return (unsigned)getNMDOps(Operands).size();
1044}
1045
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001046MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +00001047 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001048 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001049 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +00001050}
1051
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001052void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +00001053
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001054void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1055 assert(I < getNumOperands() && "Invalid operand number");
1056 getNMDOps(Operands)[I].reset(New);
1057}
1058
Devang Patel79238d72009-08-03 06:19:01 +00001059void NamedMDNode::eraseFromParent() {
Dan Gohman2637cc12010-07-21 23:38:33 +00001060 getParent()->eraseNamedMetadata(this);
Devang Patel79238d72009-08-03 06:19:01 +00001061}
1062
Devang Patel79238d72009-08-03 06:19:01 +00001063void NamedMDNode::dropAllReferences() {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001064 getNMDOps(Operands).clear();
Devang Patel79238d72009-08-03 06:19:01 +00001065}
1066
Devang Patelfcfee0f2010-01-07 19:39:36 +00001067StringRef NamedMDNode::getName() const {
1068 return StringRef(Name);
1069}
Devang Pateld5497a4b2009-09-16 18:09:00 +00001070
1071//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001072// Instruction Metadata method implementations.
1073//
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001074void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1075 for (auto &I : Attachments)
1076 if (I.first == ID) {
1077 I.second.reset(&MD);
1078 return;
1079 }
1080 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1081 std::make_tuple(&MD));
1082}
1083
1084void MDAttachmentMap::erase(unsigned ID) {
1085 if (empty())
1086 return;
1087
1088 // Common case is one/last value.
1089 if (Attachments.back().first == ID) {
1090 Attachments.pop_back();
1091 return;
1092 }
1093
1094 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1095 ++I)
1096 if (I->first == ID) {
1097 *I = std::move(Attachments.back());
1098 Attachments.pop_back();
1099 return;
1100 }
1101}
1102
1103MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1104 for (const auto &I : Attachments)
1105 if (I.first == ID)
1106 return I.second;
1107 return nullptr;
1108}
1109
1110void MDAttachmentMap::getAll(
1111 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1112 Result.append(Attachments.begin(), Attachments.end());
1113
1114 // Sort the resulting array so it is stable.
1115 if (Result.size() > 1)
1116 array_pod_sort(Result.begin(), Result.end());
1117}
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001118
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001119void MDGlobalAttachmentMap::insert(unsigned ID, MDNode &MD) {
1120 Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1121}
1122
1123void MDGlobalAttachmentMap::get(unsigned ID,
1124 SmallVectorImpl<MDNode *> &Result) {
1125 for (auto A : Attachments)
1126 if (A.MDKind == ID)
1127 Result.push_back(A.Node);
1128}
1129
1130void MDGlobalAttachmentMap::erase(unsigned ID) {
1131 auto Follower = Attachments.begin();
1132 for (auto Leader = Attachments.begin(), E = Attachments.end(); Leader != E;
1133 ++Leader) {
1134 if (Leader->MDKind != ID) {
1135 if (Follower != Leader)
1136 *Follower = std::move(*Leader);
1137 ++Follower;
1138 }
1139 }
1140 Attachments.resize(Follower - Attachments.begin());
1141}
1142
1143void MDGlobalAttachmentMap::getAll(
1144 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1145 for (auto &A : Attachments)
1146 Result.emplace_back(A.MDKind, A.Node);
1147
1148 // Sort the resulting array so it is stable with respect to metadata IDs. We
1149 // need to preserve the original insertion order though.
1150 std::stable_sort(
1151 Result.begin(), Result.end(),
1152 [](const std::pair<unsigned, MDNode *> &A,
1153 const std::pair<unsigned, MDNode *> &B) { return A.first < B.first; });
1154}
1155
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001156void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1157 if (!Node && !hasMetadata())
1158 return;
1159 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001160}
1161
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001162MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +00001163 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001164}
1165
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001166void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001167 SmallSet<unsigned, 5> KnownSet;
1168 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1169
Rafael Espindolaab73c492014-01-28 16:56:46 +00001170 if (!hasMetadataHashEntry())
1171 return; // Nothing to remove!
1172
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001173 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
Rafael Espindolaab73c492014-01-28 16:56:46 +00001174
1175 if (KnownSet.empty()) {
1176 // Just drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001177 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001178 setHasMetadataHashEntry(false);
1179 return;
1180 }
1181
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001182 auto &Info = InstructionMetadata[this];
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001183 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1184 return !KnownSet.count(I.first);
1185 });
Rafael Espindolaab73c492014-01-28 16:56:46 +00001186
Duncan P. N. Exon Smith75ef0c02015-04-24 20:23:44 +00001187 if (Info.empty()) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001188 // Drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001189 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001190 setHasMetadataHashEntry(false);
1191 }
1192}
1193
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001194void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1195 if (!Node && !hasMetadata())
1196 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001197
Chris Lattnerc263b422010-03-30 23:03:27 +00001198 // Handle 'dbg' as a special case since it is not stored in the hash table.
1199 if (KindID == LLVMContext::MD_dbg) {
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001200 DbgLoc = DebugLoc(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001201 return;
1202 }
1203
Chris Lattnera0566972009-12-29 09:01:33 +00001204 // Handle the case when we're adding/updating metadata on an instruction.
1205 if (Node) {
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001206 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001207 assert(!Info.empty() == hasMetadataHashEntry() &&
1208 "HasMetadata bit is wonked");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001209 if (Info.empty())
Chris Lattnerc263b422010-03-30 23:03:27 +00001210 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001211 Info.set(KindID, *Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001212 return;
1213 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001214
Chris Lattnera0566972009-12-29 09:01:33 +00001215 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001216 assert((hasMetadataHashEntry() ==
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001217 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001218 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001219 if (!hasMetadataHashEntry())
1220 return; // Nothing to remove!
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001221 auto &Info = getContext().pImpl->InstructionMetadata[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001222
Chris Lattnerc263b422010-03-30 23:03:27 +00001223 // Handle removal of an existing value.
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001224 Info.erase(KindID);
1225
1226 if (!Info.empty())
1227 return;
1228
1229 getContext().pImpl->InstructionMetadata.erase(this);
1230 setHasMetadataHashEntry(false);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001231}
1232
Hal Finkelcc39b672014-07-24 12:16:19 +00001233void Instruction::setAAMetadata(const AAMDNodes &N) {
1234 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001235 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1236 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001237}
1238
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001239MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001240 // Handle 'dbg' as a special case since it is not stored in the hash table.
1241 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001242 return DbgLoc.getAsMDNode();
1243
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001244 if (!hasMetadataHashEntry())
1245 return nullptr;
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001246 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001247 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001248
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001249 return Info.lookup(KindID);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001250}
1251
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001252void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001253 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001254 Result.clear();
1255
1256 // 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 +00001257 if (DbgLoc) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001258 Result.push_back(
1259 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Chris Lattnerc263b422010-03-30 23:03:27 +00001260 if (!hasMetadataHashEntry()) return;
1261 }
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001262
Chris Lattnerc263b422010-03-30 23:03:27 +00001263 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001264 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001265 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001266 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnera0566972009-12-29 09:01:33 +00001267 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001268 Info.getAll(Result);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001269}
1270
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001271void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001272 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001273 Result.clear();
1274 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001275 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001276 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001277 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001278 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001279 Info.getAll(Result);
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001280}
1281
Sanjay Pateld66607b2016-04-26 17:11:17 +00001282bool Instruction::extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) {
1283 assert((getOpcode() == Instruction::Br ||
1284 getOpcode() == Instruction::Select) &&
1285 "Looking for branch weights on something besides branch or select");
1286
1287 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1288 if (!ProfileData || ProfileData->getNumOperands() != 3)
1289 return false;
1290
1291 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1292 if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1293 return false;
1294
1295 auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
1296 auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
1297 if (!CITrue || !CIFalse)
1298 return false;
1299
1300 TrueVal = CITrue->getValue().getZExtValue();
1301 FalseVal = CIFalse->getValue().getZExtValue();
1302
1303 return true;
1304}
1305
Dehao Chen9232f982016-07-11 16:48:54 +00001306bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) {
1307 assert((getOpcode() == Instruction::Br ||
1308 getOpcode() == Instruction::Select ||
Dehao Chen71021cd2016-07-11 17:36:02 +00001309 getOpcode() == Instruction::Call ||
1310 getOpcode() == Instruction::Invoke) &&
Dehao Chen9232f982016-07-11 16:48:54 +00001311 "Looking for branch weights on something besides branch");
1312
1313 TotalVal = 0;
1314 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1315 if (!ProfileData)
1316 return false;
1317
1318 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1319 if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1320 return false;
1321
1322 TotalVal = 0;
David Majnemerdd8f6bd2016-07-11 17:09:06 +00001323 for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
Dehao Chen9232f982016-07-11 16:48:54 +00001324 auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
1325 if (!V)
1326 return false;
1327 TotalVal += V->getValue().getZExtValue();
1328 }
1329 return true;
1330}
1331
Dan Gohman48a995f2010-07-20 22:25:04 +00001332void Instruction::clearMetadataHashEntries() {
1333 assert(hasMetadataHashEntry() && "Caller should check");
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001334 getContext().pImpl->InstructionMetadata.erase(this);
Dan Gohman48a995f2010-07-20 22:25:04 +00001335 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001336}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001337
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001338void GlobalObject::getMetadata(unsigned KindID,
1339 SmallVectorImpl<MDNode *> &MDs) const {
1340 if (hasMetadata())
1341 getContext().pImpl->GlobalObjectMetadata[this].get(KindID, MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001342}
1343
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001344void GlobalObject::getMetadata(StringRef Kind,
1345 SmallVectorImpl<MDNode *> &MDs) const {
1346 if (hasMetadata())
1347 getMetadata(getContext().getMDKindID(Kind), MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001348}
1349
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001350void GlobalObject::addMetadata(unsigned KindID, MDNode &MD) {
1351 if (!hasMetadata())
1352 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001353
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001354 getContext().pImpl->GlobalObjectMetadata[this].insert(KindID, MD);
1355}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001356
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001357void GlobalObject::addMetadata(StringRef Kind, MDNode &MD) {
1358 addMetadata(getContext().getMDKindID(Kind), MD);
1359}
1360
1361void GlobalObject::eraseMetadata(unsigned KindID) {
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001362 // Nothing to unset.
1363 if (!hasMetadata())
1364 return;
1365
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001366 auto &Store = getContext().pImpl->GlobalObjectMetadata[this];
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001367 Store.erase(KindID);
1368 if (Store.empty())
1369 clearMetadata();
1370}
1371
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001372void GlobalObject::getAllMetadata(
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001373 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1374 MDs.clear();
1375
1376 if (!hasMetadata())
1377 return;
1378
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001379 getContext().pImpl->GlobalObjectMetadata[this].getAll(MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001380}
1381
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001382void GlobalObject::clearMetadata() {
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001383 if (!hasMetadata())
1384 return;
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001385 getContext().pImpl->GlobalObjectMetadata.erase(this);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001386 setHasMetadataHashEntry(false);
1387}
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001388
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001389void GlobalObject::setMetadata(unsigned KindID, MDNode *N) {
1390 eraseMetadata(KindID);
1391 if (N)
1392 addMetadata(KindID, *N);
1393}
1394
1395void GlobalObject::setMetadata(StringRef Kind, MDNode *N) {
1396 setMetadata(getContext().getMDKindID(Kind), N);
1397}
1398
1399MDNode *GlobalObject::getMetadata(unsigned KindID) const {
1400 SmallVector<MDNode *, 1> MDs;
1401 getMetadata(KindID, MDs);
1402 assert(MDs.size() <= 1 && "Expected at most one metadata attachment");
1403 if (MDs.empty())
1404 return nullptr;
1405 return MDs[0];
1406}
1407
1408MDNode *GlobalObject::getMetadata(StringRef Kind) const {
1409 return getMetadata(getContext().getMDKindID(Kind));
1410}
1411
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001412void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +00001413 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1414 Other->getAllMetadata(MDs);
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001415 for (auto &MD : MDs) {
1416 // We need to adjust the type metadata offset.
1417 if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1418 auto *OffsetConst = cast<ConstantInt>(
1419 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1420 Metadata *TypeId = MD.second->getOperand(1);
1421 auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1422 OffsetConst->getType(), OffsetConst->getValue() + Offset));
1423 addMetadata(LLVMContext::MD_type,
1424 *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1425 continue;
1426 }
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +00001427 addMetadata(MD.first, *MD.second);
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001428 }
1429}
1430
1431void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
1432 addMetadata(
1433 LLVMContext::MD_type,
1434 *MDTuple::get(getContext(),
1435 {llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1436 Type::getInt64Ty(getContext()), Offset)),
1437 TypeID}));
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +00001438}
1439
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001440void Function::setSubprogram(DISubprogram *SP) {
1441 setMetadata(LLVMContext::MD_dbg, SP);
1442}
1443
1444DISubprogram *Function::getSubprogram() const {
1445 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1446}