blob: a148ab65fc83077b6e0892dd4eab94324b4c0d88 [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
Chris Lattner1300f452009-12-28 08:24:16 +000014#include "LLVMContextImpl.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000015#include "MetadataImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "SymbolTableListTraitsImpl.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000017#include "llvm/ADT/APFloat.h"
18#include "llvm/ADT/APInt.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/None.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000022#include "llvm/ADT/STLExtras.h"
David Majnemerfa0f1e62016-08-16 18:48:34 +000023#include "llvm/ADT/SetVector.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000024#include "llvm/ADT/SmallPtrSet.h"
Rafael Espindolaab73c492014-01-28 16:56:46 +000025#include "llvm/ADT/SmallSet.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000026#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/StringMap.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000028#include "llvm/ADT/StringRef.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000029#include "llvm/ADT/Twine.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000030#include "llvm/IR/Argument.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000033#include "llvm/IR/ConstantRange.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000034#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000035#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000036#include "llvm/IR/DebugLoc.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/GlobalObject.h"
39#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Instruction.h"
41#include "llvm/IR/LLVMContext.h"
Eugene Zelenkode6cce22017-06-19 22:05:08 +000042#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Module.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000044#include "llvm/IR/TrackingMDRef.h"
45#include "llvm/IR/Type.h"
46#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000047#include "llvm/IR/ValueHandle.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000048#include "llvm/Support/Casting.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/MathExtras.h"
51#include <algorithm>
52#include <cassert>
53#include <cstddef>
54#include <cstdint>
55#include <iterator>
56#include <tuple>
Eugene Zelenkode6cce22017-06-19 22:05:08 +000057#include <type_traits>
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000058#include <utility>
59#include <vector>
Duncan P. N. Exon Smith46d91ad2014-11-14 18:42:06 +000060
Devang Patela4f43fb2009-07-28 21:49:47 +000061using namespace llvm;
62
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000063MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
64 : Value(Ty, MetadataAsValueVal), MD(MD) {
65 track();
66}
67
68MetadataAsValue::~MetadataAsValue() {
69 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
70 untrack();
71}
72
Sanjay Patel9da9c762016-03-12 20:44:58 +000073/// Canonicalize metadata arguments to intrinsics.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000074///
75/// To support bitcode upgrades (and assembly semantic sugar) for \a
76/// MetadataAsValue, we need to canonicalize certain metadata.
77///
78/// - nullptr is replaced by an empty MDNode.
79/// - An MDNode with a single null operand is replaced by an empty MDNode.
80/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
81///
82/// This maintains readability of bitcode from when metadata was a type of
83/// value, and these bridges were unnecessary.
84static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
85 Metadata *MD) {
86 if (!MD)
87 // !{}
88 return MDNode::get(Context, None);
89
90 // Return early if this isn't a single-operand MDNode.
91 auto *N = dyn_cast<MDNode>(MD);
92 if (!N || N->getNumOperands() != 1)
93 return MD;
94
95 if (!N->getOperand(0))
96 // !{}
97 return MDNode::get(Context, None);
98
99 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
100 // Look through the MDNode.
101 return C;
102
103 return MD;
104}
105
106MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
107 MD = canonicalizeMetadataForValue(Context, MD);
108 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
109 if (!Entry)
110 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
111 return Entry;
112}
113
114MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
115 Metadata *MD) {
116 MD = canonicalizeMetadataForValue(Context, MD);
117 auto &Store = Context.pImpl->MetadataAsValues;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000118 return Store.lookup(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000119}
120
121void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
122 LLVMContext &Context = getContext();
123 MD = canonicalizeMetadataForValue(Context, MD);
124 auto &Store = Context.pImpl->MetadataAsValues;
125
126 // Stop tracking the old metadata.
127 Store.erase(this->MD);
128 untrack();
129 this->MD = nullptr;
130
131 // Start tracking MD, or RAUW if necessary.
132 auto *&Entry = Store[MD];
133 if (Entry) {
134 replaceAllUsesWith(Entry);
135 delete this;
136 return;
137 }
138
139 this->MD = MD;
140 track();
141 Entry = this;
142}
143
144void MetadataAsValue::track() {
145 if (MD)
146 MetadataTracking::track(&MD, *MD, *this);
147}
148
149void MetadataAsValue::untrack() {
150 if (MD)
151 MetadataTracking::untrack(MD);
152}
153
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000154bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
155 assert(Ref && "Expected live reference");
156 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
157 "Reference without owner must be direct");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000158 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000159 R->addRef(Ref, Owner);
160 return true;
161 }
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000162 if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
163 assert(!PH->Use && "Placeholders can only be used once");
164 assert(!Owner && "Unexpected callback to owner");
165 PH->Use = static_cast<Metadata **>(Ref);
166 return true;
167 }
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000168 return false;
169}
170
171void MetadataTracking::untrack(void *Ref, Metadata &MD) {
172 assert(Ref && "Expected live reference");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000173 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000174 R->dropRef(Ref);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000175 else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
176 PH->Use = nullptr;
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000177}
178
179bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
180 assert(Ref && "Expected live reference");
181 assert(New && "Expected live reference");
182 assert(Ref != New && "Expected change");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000183 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000184 R->moveRef(Ref, New, MD);
185 return true;
186 }
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000187 assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
188 "Unexpected move of an MDOperand");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000189 assert(!isReplaceable(MD) &&
190 "Expected un-replaceable metadata, since we didn't move a reference");
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000191 return false;
192}
193
194bool MetadataTracking::isReplaceable(const Metadata &MD) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000195 return ReplaceableMetadataImpl::isReplaceable(MD);
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000196}
197
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000198void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000199 bool WasInserted =
200 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
201 .second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000202 (void)WasInserted;
203 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000204
205 ++NextIndex;
206 assert(NextIndex != 0 && "Unexpected overflow");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000207}
208
209void ReplaceableMetadataImpl::dropRef(void *Ref) {
210 bool WasErased = UseMap.erase(Ref);
211 (void)WasErased;
212 assert(WasErased && "Expected to drop a reference");
213}
214
215void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
216 const Metadata &MD) {
217 auto I = UseMap.find(Ref);
218 assert(I != UseMap.end() && "Expected to move a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000219 auto OwnerAndIndex = I->second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000220 UseMap.erase(I);
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000221 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
222 (void)WasInserted;
223 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000224
225 // Check that the references are direct if there's no owner.
226 (void)MD;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000227 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000228 "Reference without owner must be direct");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000229 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000230 "Reference without owner must be direct");
231}
232
233void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000234 if (UseMap.empty())
235 return;
236
237 // Copy out uses since UseMap will get touched below.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000238 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000239 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
240 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
241 return L.second.second < R.second.second;
242 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000243 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith4a4f7852015-01-14 19:56:10 +0000244 // Check that this Ref hasn't disappeared after RAUW (when updating a
245 // previous Ref).
246 if (!UseMap.count(Pair.first))
247 continue;
248
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000249 OwnerTy Owner = Pair.second.first;
250 if (!Owner) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000251 // Update unowned tracking references directly.
252 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
253 Ref = MD;
Duncan P. N. Exon Smith121eeff2014-12-12 19:24:33 +0000254 if (MD)
255 MetadataTracking::track(Ref);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000256 UseMap.erase(Pair.first);
257 continue;
258 }
259
260 // Check for MetadataAsValue.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000261 if (Owner.is<MetadataAsValue *>()) {
262 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000263 continue;
264 }
265
266 // There's a Metadata owner -- dispatch.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000267 Metadata *OwnerMD = Owner.get<Metadata *>();
268 switch (OwnerMD->getMetadataID()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000269#define HANDLE_METADATA_LEAF(CLASS) \
270 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000271 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000272 continue;
273#include "llvm/IR/Metadata.def"
274 default:
275 llvm_unreachable("Invalid metadata subclass");
276 }
277 }
278 assert(UseMap.empty() && "Expected all uses to be replaced");
279}
280
281void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
282 if (UseMap.empty())
283 return;
284
285 if (!ResolveUsers) {
286 UseMap.clear();
287 return;
288 }
289
290 // Copy out uses since UseMap could get touched below.
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000291 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000292 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
293 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
294 return L.second.second < R.second.second;
295 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000296 UseMap.clear();
297 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000298 auto Owner = Pair.second.first;
299 if (!Owner)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000300 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000301 if (Owner.is<MetadataAsValue *>())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000302 continue;
303
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000304 // Resolve MDNodes that point at this.
305 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000306 if (!OwnerMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000307 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000308 if (OwnerMD->isResolved())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000309 continue;
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000310 OwnerMD->decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000311 }
312}
313
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000314ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000315 if (auto *N = dyn_cast<MDNode>(&MD))
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000316 return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
317 return dyn_cast<ValueAsMetadata>(&MD);
318}
319
320ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
321 if (auto *N = dyn_cast<MDNode>(&MD))
322 return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
323 return dyn_cast<ValueAsMetadata>(&MD);
324}
325
326bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
327 if (auto *N = dyn_cast<MDNode>(&MD))
328 return !N->isResolved();
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000329 return dyn_cast<ValueAsMetadata>(&MD);
330}
331
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000332static Function *getLocalFunction(Value *V) {
333 assert(V && "Expected value");
334 if (auto *A = dyn_cast<Argument>(V))
335 return A->getParent();
336 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
337 return BB->getParent();
338 return nullptr;
339}
340
341ValueAsMetadata *ValueAsMetadata::get(Value *V) {
342 assert(V && "Unexpected null Value");
343
344 auto &Context = V->getContext();
345 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
346 if (!Entry) {
347 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
348 "Expected constant or function-local value");
Dehao Chene0e0ed12016-09-16 18:27:20 +0000349 assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000350 V->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000351 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000352 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000353 else
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000354 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000355 }
356
357 return Entry;
358}
359
360ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
361 assert(V && "Unexpected null Value");
362 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
363}
364
365void ValueAsMetadata::handleDeletion(Value *V) {
366 assert(V && "Expected valid value");
367
368 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
369 auto I = Store.find(V);
370 if (I == Store.end())
371 return;
372
373 // Remove old entry from the map.
374 ValueAsMetadata *MD = I->second;
375 assert(MD && "Expected valid metadata");
376 assert(MD->getValue() == V && "Expected valid mapping");
377 Store.erase(I);
378
379 // Delete the metadata.
380 MD->replaceAllUsesWith(nullptr);
381 delete MD;
382}
383
384void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
385 assert(From && "Expected valid value");
386 assert(To && "Expected valid value");
387 assert(From != To && "Expected changed value");
388 assert(From->getType() == To->getType() && "Unexpected type change");
389
390 LLVMContext &Context = From->getType()->getContext();
391 auto &Store = Context.pImpl->ValuesAsMetadata;
392 auto I = Store.find(From);
393 if (I == Store.end()) {
Dehao Chene0e0ed12016-09-16 18:27:20 +0000394 assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000395 return;
396 }
397
398 // Remove old entry from the map.
Dehao Chene0e0ed12016-09-16 18:27:20 +0000399 assert(From->IsUsedByMD && "Expected From to be used by metadata");
Owen Anderson7349ab92015-06-01 22:24:01 +0000400 From->IsUsedByMD = false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000401 ValueAsMetadata *MD = I->second;
402 assert(MD && "Expected valid metadata");
403 assert(MD->getValue() == From && "Expected valid mapping");
404 Store.erase(I);
405
406 if (isa<LocalAsMetadata>(MD)) {
407 if (auto *C = dyn_cast<Constant>(To)) {
408 // Local became a constant.
409 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
410 delete MD;
411 return;
412 }
413 if (getLocalFunction(From) && getLocalFunction(To) &&
414 getLocalFunction(From) != getLocalFunction(To)) {
415 // Function changed.
416 MD->replaceAllUsesWith(nullptr);
417 delete MD;
418 return;
419 }
420 } else if (!isa<Constant>(To)) {
421 // Changed to function-local value.
422 MD->replaceAllUsesWith(nullptr);
423 delete MD;
424 return;
425 }
426
427 auto *&Entry = Store[To];
428 if (Entry) {
429 // The target already exists.
430 MD->replaceAllUsesWith(Entry);
431 delete MD;
432 return;
433 }
434
435 // Update MD in place (and update the map entry).
Dehao Chene0e0ed12016-09-16 18:27:20 +0000436 assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000437 To->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000438 MD->V = To;
439 Entry = MD;
440}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000441
Devang Patela4f43fb2009-07-28 21:49:47 +0000442//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000443// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000444//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000445
Devang Pateldcb99d32009-10-22 00:10:15 +0000446MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000447 auto &Store = Context.pImpl->MDStringCache;
Benjamin Kramereab3d362016-07-21 13:37:48 +0000448 auto I = Store.try_emplace(Str);
Mehdi Aminicb708b22016-03-25 05:58:04 +0000449 auto &MapEntry = I.first->getValue();
450 if (!I.second)
451 return &MapEntry;
452 MapEntry.Entry = &*I.first;
453 return &MapEntry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000454}
455
456StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000457 assert(Entry && "Expected to find string map entry");
458 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000459}
460
461//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000462// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000463//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000464
James Y Knight8096d342015-06-17 01:21:20 +0000465// Assert that the MDNode types will not be unaligned by the objects
466// prepended to them.
467#define HANDLE_MDNODE_LEAF(CLASS) \
James Y Knightf27e4412015-06-17 13:53:12 +0000468 static_assert( \
Benjamin Kramerb2505002016-10-20 15:02:18 +0000469 alignof(uint64_t) >= alignof(CLASS), \
James Y Knightf27e4412015-06-17 13:53:12 +0000470 "Alignment is insufficient after objects prepended to " #CLASS);
James Y Knight8096d342015-06-17 01:21:20 +0000471#include "llvm/IR/Metadata.def"
472
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000473void *MDNode::operator new(size_t Size, unsigned NumOps) {
James Y Knight8096d342015-06-17 01:21:20 +0000474 size_t OpSize = NumOps * sizeof(MDOperand);
475 // uint64_t is the most aligned type we need support (ensured by static_assert
476 // above)
Benjamin Kramerb2505002016-10-20 15:02:18 +0000477 OpSize = alignTo(OpSize, alignof(uint64_t));
James Y Knight8096d342015-06-17 01:21:20 +0000478 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000479 MDOperand *O = static_cast<MDOperand *>(Ptr);
James Y Knight8096d342015-06-17 01:21:20 +0000480 for (MDOperand *E = O - NumOps; O != E; --O)
481 (void)new (O - 1) MDOperand;
482 return Ptr;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000483}
484
Naomi Musgrave21c1bc42015-08-31 21:06:08 +0000485void MDNode::operator delete(void *Mem) {
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000486 MDNode *N = static_cast<MDNode *>(Mem);
James Y Knight8096d342015-06-17 01:21:20 +0000487 size_t OpSize = N->NumOperands * sizeof(MDOperand);
Benjamin Kramerb2505002016-10-20 15:02:18 +0000488 OpSize = alignTo(OpSize, alignof(uint64_t));
James Y Knight8096d342015-06-17 01:21:20 +0000489
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000490 MDOperand *O = static_cast<MDOperand *>(Mem);
491 for (MDOperand *E = O - N->NumOperands; O != E; --O)
492 (O - 1)->~MDOperand();
James Y Knight8096d342015-06-17 01:21:20 +0000493 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000494}
495
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000496MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000497 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
498 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
499 NumUnresolved(0), Context(Context) {
500 unsigned Op = 0;
501 for (Metadata *MD : Ops1)
502 setOperand(Op++, MD);
503 for (Metadata *MD : Ops2)
504 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000505
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000506 if (!isUniqued())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000507 return;
508
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000509 // Count the unresolved operands. If there are any, RAUW support will be
510 // added lazily on first reference.
511 countUnresolvedOperands();
Devang Patela4f43fb2009-07-28 21:49:47 +0000512}
513
Duncan P. N. Exon Smith03e05832015-01-20 02:56:57 +0000514TempMDNode MDNode::clone() const {
515 switch (getMetadataID()) {
516 default:
517 llvm_unreachable("Invalid MDNode subclass");
518#define HANDLE_MDNODE_LEAF(CLASS) \
519 case CLASS##Kind: \
520 return cast<CLASS>(this)->cloneImpl();
521#include "llvm/IR/Metadata.def"
522 }
523}
524
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000525static bool isOperandUnresolved(Metadata *Op) {
526 if (auto *N = dyn_cast_or_null<MDNode>(Op))
527 return !N->isResolved();
528 return false;
529}
530
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000531void MDNode::countUnresolvedOperands() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000532 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000533 assert(isUniqued() && "Expected this to be uniqued");
Sanjoy Das39c226f2016-06-10 21:18:39 +0000534 NumUnresolved = count_if(operands(), isOperandUnresolved);
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000535}
536
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000537void MDNode::makeUniqued() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000538 assert(isTemporary() && "Expected this to be temporary");
539 assert(!isResolved() && "Expected this to be unresolved");
540
Duncan P. N. Exon Smithcb33d6f2015-03-31 20:50:50 +0000541 // Enable uniquing callbacks.
542 for (auto &Op : mutable_operands())
543 Op.reset(Op.get(), this);
544
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000545 // Make this 'uniqued'.
546 Storage = Uniqued;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000547 countUnresolvedOperands();
548 if (!NumUnresolved) {
549 dropReplaceableUses();
550 assert(isResolved() && "Expected this to be resolved");
551 }
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000552
553 assert(isUniqued() && "Expected this to be uniqued");
554}
555
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000556void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000557 assert(isTemporary() && "Expected this to be temporary");
558 assert(!isResolved() && "Expected this to be unresolved");
559
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000560 // Drop RAUW support and store as a distinct node.
561 dropReplaceableUses();
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000562 storeDistinctInContext();
563
564 assert(isDistinct() && "Expected this to be distinct");
565 assert(isResolved() && "Expected this to be resolved");
566}
567
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000568void MDNode::resolve() {
Duncan P. N. Exon Smithb8f79602015-01-19 19:26:24 +0000569 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000570 assert(!isResolved() && "Expected this to be unresolved");
571
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000572 NumUnresolved = 0;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000573 dropReplaceableUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000574
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000575 assert(isResolved() && "Expected this to be resolved");
576}
577
578void MDNode::dropReplaceableUses() {
579 assert(!NumUnresolved && "Unexpected unresolved operand");
580
581 // Drop any RAUW support.
582 if (Context.hasReplaceableUses())
583 Context.takeReplaceableUses()->resolveAllUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000584}
585
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000586void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000587 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000588 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000589
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000590 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000591 if (!isOperandUnresolved(Old)) {
592 if (isOperandUnresolved(New))
593 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000594 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000595 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000596 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000597}
598
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000599void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000600 assert(!isResolved() && "Expected this to be unresolved");
601 if (isTemporary())
602 return;
603
604 assert(isUniqued() && "Expected this to be uniqued");
605 if (--NumUnresolved)
606 return;
607
608 // Last unresolved operand has just been resolved.
609 dropReplaceableUses();
610 assert(isResolved() && "Expected this to become resolved");
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000611}
612
Teresa Johnsonb703c772016-03-29 18:24:19 +0000613void MDNode::resolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000614 if (isResolved())
615 return;
616
617 // Resolve this node immediately.
618 resolve();
619
620 // Resolve all operands.
621 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000622 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000623 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000624 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000625
626 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000627 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000628 if (!N->isResolved())
629 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000630 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000631}
632
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000633static bool hasSelfReference(MDNode *N) {
634 for (Metadata *MD : N->operands())
635 if (MD == N)
636 return true;
637 return false;
638}
639
640MDNode *MDNode::replaceWithPermanentImpl() {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000641 switch (getMetadataID()) {
642 default:
643 // If this type isn't uniquable, replace with a distinct node.
644 return replaceWithDistinctImpl();
645
646#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
647 case CLASS##Kind: \
648 break;
649#include "llvm/IR/Metadata.def"
650 }
651
652 // Even if this type is uniquable, self-references have to be distinct.
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000653 if (hasSelfReference(this))
654 return replaceWithDistinctImpl();
655 return replaceWithUniquedImpl();
656}
657
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000658MDNode *MDNode::replaceWithUniquedImpl() {
659 // Try to uniquify in place.
660 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000661
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000662 if (UniquedNode == this) {
663 makeUniqued();
664 return this;
665 }
666
667 // Collision, so RAUW instead.
668 replaceAllUsesWith(UniquedNode);
669 deleteAsSubclass();
670 return UniquedNode;
671}
672
673MDNode *MDNode::replaceWithDistinctImpl() {
674 makeDistinct();
675 return this;
676}
677
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000678void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000679 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000680}
681
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000682void MDNode::dropAllReferences() {
683 for (unsigned I = 0, E = NumOperands; I != E; ++I)
684 setOperand(I, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000685 if (Context.hasReplaceableUses()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000686 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
687 (void)Context.takeReplaceableUses();
688 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000689}
690
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000691void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000692 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
693 assert(Op < getNumOperands() && "Expected valid operand");
694
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000695 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000696 // This node is not uniqued. Just set the operand and be done with it.
697 setOperand(Op, New);
698 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000699 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000700
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000701 // This node is uniqued.
702 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000703
704 Metadata *Old = getOperand(Op);
705 setOperand(Op, New);
706
Duncan P. N. Exon Smith9cbc69d2016-08-03 18:19:43 +0000707 // Drop uniquing for self-reference cycles and deleted constants.
708 if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000709 if (!isResolved())
710 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000711 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000712 return;
713 }
714
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000715 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000716 auto *Uniqued = uniquify();
717 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000718 if (!isResolved())
719 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000720 return;
721 }
722
723 // Collision.
724 if (!isResolved()) {
725 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000726 //
727 // First, clear out all operands to prevent any recursion (similar to
728 // dropAllReferences(), but we still need the use-list).
729 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
730 setOperand(O, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000731 if (Context.hasReplaceableUses())
732 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000733 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000734 return;
735 }
736
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000737 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000738 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000739}
740
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000741void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000742 switch (getMetadataID()) {
743 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000744 llvm_unreachable("Invalid subclass of MDNode");
745#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000746 case CLASS##Kind: \
747 delete cast<CLASS>(this); \
748 break;
749#include "llvm/IR/Metadata.def"
750 }
751}
752
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000753template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000754static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
755 if (T *U = getUniqued(Store, N))
756 return U;
757
758 Store.insert(N);
759 return N;
760}
761
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000762template <class NodeTy> struct MDNode::HasCachedHash {
Eugene Zelenkode6cce22017-06-19 22:05:08 +0000763 using Yes = char[1];
764 using No = char[2];
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000765 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000766
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000767 template <class U>
768 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
769 template <class U> static No &check(...);
770
771 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
772};
773
774MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000775 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
776
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000777 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000778 switch (getMetadataID()) {
779 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000780 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
781#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000782 case CLASS##Kind: { \
783 CLASS *SubclassThis = cast<CLASS>(this); \
784 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
785 ShouldRecalculateHash; \
786 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
787 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
788 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000789#include "llvm/IR/Metadata.def"
790 }
791}
792
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000793void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000794 switch (getMetadataID()) {
795 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000796 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
797#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000798 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000799 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000800 break;
801#include "llvm/IR/Metadata.def"
802 }
803}
804
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000805MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000806 StorageType Storage, bool ShouldCreate) {
807 unsigned Hash = 0;
808 if (Storage == Uniqued) {
809 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000810 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
811 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000812 if (!ShouldCreate)
813 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000814 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000815 } else {
816 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
817 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000818
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000819 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
820 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000821}
822
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000823void MDNode::deleteTemporary(MDNode *N) {
824 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000825 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000826 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000827}
828
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000829void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000830 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
831 assert(!NumUnresolved && "Unexpected unresolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000832 Storage = Distinct;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000833 assert(isResolved() && "Expected this to be resolved");
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000834
835 // Reset the hash.
836 switch (getMetadataID()) {
837 default:
838 llvm_unreachable("Invalid subclass of MDNode");
839#define HANDLE_MDNODE_LEAF(CLASS) \
840 case CLASS##Kind: { \
841 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
842 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
843 break; \
844 }
845#include "llvm/IR/Metadata.def"
846 }
847
Duncan P. N. Exon Smith3eef9d12016-04-19 23:59:13 +0000848 getContext().pImpl->DistinctMDNodes.push_back(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000849}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000850
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000851void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
852 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000853 return;
Devang Patelf7188322009-09-03 01:39:20 +0000854
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000855 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000856 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000857 return;
858 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000859
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000860 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000861}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000862
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000863void MDNode::setOperand(unsigned I, Metadata *New) {
864 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000865 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000866}
867
Sanjay Patel9da9c762016-03-12 20:44:58 +0000868/// Get a node or a self-reference that looks like it.
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000869///
870/// Special handling for finding self-references, for use by \a
871/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
872/// when self-referencing nodes were still uniqued. If the first operand has
873/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000874static MDNode *getOrSelfReference(LLVMContext &Context,
875 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000876 if (!Ops.empty())
877 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
878 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
879 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
880 if (Ops[I] != N->getOperand(I))
881 return MDNode::get(Context, Ops);
882 return N;
883 }
884
885 return MDNode::get(Context, Ops);
886}
887
Hal Finkel94146652014-07-24 14:25:39 +0000888MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
889 if (!A)
890 return B;
891 if (!B)
892 return A;
893
David Majnemerfa0f1e62016-08-16 18:48:34 +0000894 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
895 MDs.insert(B->op_begin(), B->op_end());
Hal Finkel94146652014-07-24 14:25:39 +0000896
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000897 // FIXME: This preserves long-standing behaviour, but is it really the right
898 // behaviour? Or was that an unintended side-effect of node uniquing?
David Majnemerfa0f1e62016-08-16 18:48:34 +0000899 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
Hal Finkel94146652014-07-24 14:25:39 +0000900}
901
902MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
903 if (!A || !B)
904 return nullptr;
905
David Majnemer00940fb2016-08-16 18:48:37 +0000906 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
907 SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
908 MDs.remove_if([&](Metadata *MD) { return !is_contained(BSet, MD); });
Hal Finkel94146652014-07-24 14:25:39 +0000909
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000910 // FIXME: This preserves long-standing behaviour, but is it really the right
911 // behaviour? Or was that an unintended side-effect of node uniquing?
David Majnemer00940fb2016-08-16 18:48:37 +0000912 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
Hal Finkel94146652014-07-24 14:25:39 +0000913}
914
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000915MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
916 if (!A || !B)
917 return nullptr;
918
David Majnemerfa0f1e62016-08-16 18:48:34 +0000919 return concatenate(A, B);
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000920}
921
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000922MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
923 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000924 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000925
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000926 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
927 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000928 if (AVal.compare(BVal) == APFloat::cmpLessThan)
929 return A;
930 return B;
931}
932
933static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
934 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
935}
936
937static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
938 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
939}
940
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000941static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
942 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000943 ConstantRange NewRange(Low->getValue(), High->getValue());
944 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000945 APInt LB = EndPoints[Size - 2]->getValue();
946 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000947 ConstantRange LastRange(LB, LE);
948 if (canBeMerged(NewRange, LastRange)) {
949 ConstantRange Union = LastRange.unionWith(NewRange);
950 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000951 EndPoints[Size - 2] =
952 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
953 EndPoints[Size - 1] =
954 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000955 return true;
956 }
957 return false;
958}
959
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000960static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
961 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000962 if (!EndPoints.empty())
963 if (tryMergeRange(EndPoints, Low, High))
964 return;
965
966 EndPoints.push_back(Low);
967 EndPoints.push_back(High);
968}
969
970MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
971 // Given two ranges, we want to compute the union of the ranges. This
Craig Topperabd6b1d2017-04-27 05:48:29 +0000972 // is slightly complicated by having to combine the intervals and merge
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000973 // the ones that overlap.
974
975 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000976 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000977
978 if (A == B)
979 return A;
980
Craig Topperabd6b1d2017-04-27 05:48:29 +0000981 // First, walk both lists in order of the lower boundary of each interval.
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000982 // 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 +0000983 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000984 int AI = 0;
985 int BI = 0;
986 int AN = A->getNumOperands() / 2;
987 int BN = B->getNumOperands() / 2;
988 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000989 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
990 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000991
992 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000993 addRange(EndPoints, ALow,
994 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000995 ++AI;
996 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000997 addRange(EndPoints, BLow,
998 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000999 ++BI;
1000 }
1001 }
1002 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001003 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1004 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001005 ++AI;
1006 }
1007 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001008 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1009 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001010 ++BI;
1011 }
1012
1013 // If we have more than 2 ranges (4 endpoints) we have to try to merge
1014 // the last and first ones.
1015 unsigned Size = EndPoints.size();
1016 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001017 ConstantInt *FB = EndPoints[0];
1018 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001019 if (tryMergeRange(EndPoints, FB, FE)) {
1020 for (unsigned i = 0; i < Size - 2; ++i) {
1021 EndPoints[i] = EndPoints[i + 2];
1022 }
1023 EndPoints.resize(Size - 2);
1024 }
1025 }
1026
1027 // If in the end we have a single range, it is possible that it is now the
1028 // full range. Just drop the metadata in that case.
1029 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001030 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001031 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +00001032 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001033 }
1034
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001035 SmallVector<Metadata *, 4> MDs;
1036 MDs.reserve(EndPoints.size());
1037 for (auto *I : EndPoints)
1038 MDs.push_back(ConstantAsMetadata::get(I));
1039 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001040}
1041
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001042MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1043 if (!A || !B)
1044 return nullptr;
1045
1046 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1047 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1048 if (AVal->getZExtValue() < BVal->getZExtValue())
1049 return A;
1050 return B;
1051}
1052
Devang Patel05a26fb2009-07-29 00:33:07 +00001053//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +00001054// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +00001055//
Devang Patel943ddf62010-01-12 18:34:06 +00001056
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001057static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1058 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +00001059}
1060
Dan Gohman2637cc12010-07-21 23:38:33 +00001061NamedMDNode::NamedMDNode(const Twine &N)
Eugene Zelenkodeaf6952017-02-17 00:00:09 +00001062 : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +00001063
Chris Lattner1bc810b2009-12-28 08:07:14 +00001064NamedMDNode::~NamedMDNode() {
1065 dropAllReferences();
1066 delete &getNMDOps(Operands);
1067}
1068
Chris Lattner9b493022009-12-31 01:22:29 +00001069unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001070 return (unsigned)getNMDOps(Operands).size();
1071}
1072
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001073MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +00001074 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001075 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001076 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +00001077}
1078
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001079void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +00001080
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001081void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1082 assert(I < getNumOperands() && "Invalid operand number");
1083 getNMDOps(Operands)[I].reset(New);
1084}
1085
Dehao Chene0e0ed12016-09-16 18:27:20 +00001086void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
Devang Patel79238d72009-08-03 06:19:01 +00001087
Michael Ilsemane5428042016-10-25 18:44:13 +00001088void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
Devang Patel79238d72009-08-03 06:19:01 +00001089
Dehao Chene0e0ed12016-09-16 18:27:20 +00001090StringRef NamedMDNode::getName() const { return StringRef(Name); }
Devang Pateld5497a4b2009-09-16 18:09:00 +00001091
1092//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001093// Instruction Metadata method implementations.
1094//
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001095void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1096 for (auto &I : Attachments)
1097 if (I.first == ID) {
1098 I.second.reset(&MD);
1099 return;
1100 }
1101 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1102 std::make_tuple(&MD));
1103}
1104
1105void MDAttachmentMap::erase(unsigned ID) {
1106 if (empty())
1107 return;
1108
1109 // Common case is one/last value.
1110 if (Attachments.back().first == ID) {
1111 Attachments.pop_back();
1112 return;
1113 }
1114
1115 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1116 ++I)
1117 if (I->first == ID) {
1118 *I = std::move(Attachments.back());
1119 Attachments.pop_back();
1120 return;
1121 }
1122}
1123
1124MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1125 for (const auto &I : Attachments)
1126 if (I.first == ID)
1127 return I.second;
1128 return nullptr;
1129}
1130
1131void MDAttachmentMap::getAll(
1132 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1133 Result.append(Attachments.begin(), Attachments.end());
1134
1135 // Sort the resulting array so it is stable.
1136 if (Result.size() > 1)
1137 array_pod_sort(Result.begin(), Result.end());
1138}
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001139
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001140void MDGlobalAttachmentMap::insert(unsigned ID, MDNode &MD) {
1141 Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1142}
1143
1144void MDGlobalAttachmentMap::get(unsigned ID,
1145 SmallVectorImpl<MDNode *> &Result) {
1146 for (auto A : Attachments)
1147 if (A.MDKind == ID)
1148 Result.push_back(A.Node);
1149}
1150
1151void MDGlobalAttachmentMap::erase(unsigned ID) {
1152 auto Follower = Attachments.begin();
1153 for (auto Leader = Attachments.begin(), E = Attachments.end(); Leader != E;
1154 ++Leader) {
1155 if (Leader->MDKind != ID) {
1156 if (Follower != Leader)
1157 *Follower = std::move(*Leader);
1158 ++Follower;
1159 }
1160 }
1161 Attachments.resize(Follower - Attachments.begin());
1162}
1163
1164void MDGlobalAttachmentMap::getAll(
1165 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1166 for (auto &A : Attachments)
1167 Result.emplace_back(A.MDKind, A.Node);
1168
1169 // Sort the resulting array so it is stable with respect to metadata IDs. We
1170 // need to preserve the original insertion order though.
1171 std::stable_sort(
1172 Result.begin(), Result.end(),
1173 [](const std::pair<unsigned, MDNode *> &A,
1174 const std::pair<unsigned, MDNode *> &B) { return A.first < B.first; });
1175}
1176
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001177void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1178 if (!Node && !hasMetadata())
1179 return;
1180 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001181}
1182
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001183MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +00001184 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001185}
1186
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001187void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001188 if (!hasMetadataHashEntry())
1189 return; // Nothing to remove!
1190
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001191 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
Rafael Espindolaab73c492014-01-28 16:56:46 +00001192
Aditya Kumar0a48b372016-09-26 21:01:13 +00001193 SmallSet<unsigned, 4> KnownSet;
1194 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
Rafael Espindolaab73c492014-01-28 16:56:46 +00001195 if (KnownSet.empty()) {
1196 // Just drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001197 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001198 setHasMetadataHashEntry(false);
1199 return;
1200 }
1201
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001202 auto &Info = InstructionMetadata[this];
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001203 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1204 return !KnownSet.count(I.first);
1205 });
Rafael Espindolaab73c492014-01-28 16:56:46 +00001206
Duncan P. N. Exon Smith75ef0c02015-04-24 20:23:44 +00001207 if (Info.empty()) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001208 // Drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001209 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001210 setHasMetadataHashEntry(false);
1211 }
1212}
1213
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001214void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1215 if (!Node && !hasMetadata())
1216 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001217
Chris Lattnerc263b422010-03-30 23:03:27 +00001218 // Handle 'dbg' as a special case since it is not stored in the hash table.
1219 if (KindID == LLVMContext::MD_dbg) {
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001220 DbgLoc = DebugLoc(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001221 return;
1222 }
Dehao Chene0e0ed12016-09-16 18:27:20 +00001223
Chris Lattnera0566972009-12-29 09:01:33 +00001224 // Handle the case when we're adding/updating metadata on an instruction.
1225 if (Node) {
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001226 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001227 assert(!Info.empty() == hasMetadataHashEntry() &&
1228 "HasMetadata bit is wonked");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001229 if (Info.empty())
Chris Lattnerc263b422010-03-30 23:03:27 +00001230 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001231 Info.set(KindID, *Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001232 return;
1233 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001234
Chris Lattnera0566972009-12-29 09:01:33 +00001235 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001236 assert((hasMetadataHashEntry() ==
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001237 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001238 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001239 if (!hasMetadataHashEntry())
Dehao Chene0e0ed12016-09-16 18:27:20 +00001240 return; // Nothing to remove!
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001241 auto &Info = getContext().pImpl->InstructionMetadata[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001242
Chris Lattnerc263b422010-03-30 23:03:27 +00001243 // Handle removal of an existing value.
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001244 Info.erase(KindID);
1245
1246 if (!Info.empty())
1247 return;
1248
1249 getContext().pImpl->InstructionMetadata.erase(this);
1250 setHasMetadataHashEntry(false);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001251}
1252
Hal Finkelcc39b672014-07-24 12:16:19 +00001253void Instruction::setAAMetadata(const AAMDNodes &N) {
1254 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001255 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1256 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001257}
1258
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001259MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001260 // Handle 'dbg' as a special case since it is not stored in the hash table.
1261 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001262 return DbgLoc.getAsMDNode();
1263
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001264 if (!hasMetadataHashEntry())
1265 return nullptr;
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001266 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001267 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001268
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001269 return Info.lookup(KindID);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001270}
1271
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001272void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001273 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001274 Result.clear();
Dehao Chene0e0ed12016-09-16 18:27:20 +00001275
Chris Lattnerc263b422010-03-30 23:03:27 +00001276 // 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 +00001277 if (DbgLoc) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001278 Result.push_back(
1279 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Dehao Chene0e0ed12016-09-16 18:27:20 +00001280 if (!hasMetadataHashEntry())
1281 return;
Chris Lattnerc263b422010-03-30 23:03:27 +00001282 }
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001283
Chris Lattnerc263b422010-03-30 23:03:27 +00001284 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001285 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001286 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001287 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnera0566972009-12-29 09:01:33 +00001288 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001289 Info.getAll(Result);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001290}
1291
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001292void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001293 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001294 Result.clear();
1295 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001296 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001297 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001298 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001299 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001300 Info.getAll(Result);
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001301}
1302
Dehao Chene0e0ed12016-09-16 18:27:20 +00001303bool Instruction::extractProfMetadata(uint64_t &TrueVal,
1304 uint64_t &FalseVal) const {
1305 assert(
1306 (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
1307 "Looking for branch weights on something besides branch or select");
Sanjay Pateld66607b2016-04-26 17:11:17 +00001308
1309 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1310 if (!ProfileData || ProfileData->getNumOperands() != 3)
1311 return false;
1312
1313 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1314 if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1315 return false;
1316
1317 auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
1318 auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
1319 if (!CITrue || !CIFalse)
1320 return false;
1321
1322 TrueVal = CITrue->getValue().getZExtValue();
1323 FalseVal = CIFalse->getValue().getZExtValue();
1324
1325 return true;
1326}
1327
Dehao Chene0e0ed12016-09-16 18:27:20 +00001328bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
Dehao Chen9232f982016-07-11 16:48:54 +00001329 assert((getOpcode() == Instruction::Br ||
1330 getOpcode() == Instruction::Select ||
Dehao Chen71021cd2016-07-11 17:36:02 +00001331 getOpcode() == Instruction::Call ||
Dehao Chene9d07522016-10-11 18:53:00 +00001332 getOpcode() == Instruction::Invoke ||
1333 getOpcode() == Instruction::Switch) &&
Dehao Chen9232f982016-07-11 16:48:54 +00001334 "Looking for branch weights on something besides branch");
1335
1336 TotalVal = 0;
1337 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1338 if (!ProfileData)
1339 return false;
1340
1341 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
Dehao Chenfed890e2017-03-31 15:59:52 +00001342 if (!ProfDataName)
Dehao Chen9232f982016-07-11 16:48:54 +00001343 return false;
1344
Dehao Chenfed890e2017-03-31 15:59:52 +00001345 if (ProfDataName->getString().equals("branch_weights")) {
1346 TotalVal = 0;
1347 for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
1348 auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
1349 if (!V)
1350 return false;
1351 TotalVal += V->getValue().getZExtValue();
1352 }
1353 return true;
1354 } else if (ProfDataName->getString().equals("VP") &&
1355 ProfileData->getNumOperands() > 3) {
1356 TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
1357 ->getValue()
1358 .getZExtValue();
1359 return true;
Dehao Chen9232f982016-07-11 16:48:54 +00001360 }
Dehao Chenfed890e2017-03-31 15:59:52 +00001361 return false;
Dehao Chen9232f982016-07-11 16:48:54 +00001362}
1363
Dan Gohman48a995f2010-07-20 22:25:04 +00001364void Instruction::clearMetadataHashEntries() {
1365 assert(hasMetadataHashEntry() && "Caller should check");
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001366 getContext().pImpl->InstructionMetadata.erase(this);
Dan Gohman48a995f2010-07-20 22:25:04 +00001367 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001368}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001369
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001370void GlobalObject::getMetadata(unsigned KindID,
1371 SmallVectorImpl<MDNode *> &MDs) const {
1372 if (hasMetadata())
1373 getContext().pImpl->GlobalObjectMetadata[this].get(KindID, MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001374}
1375
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001376void GlobalObject::getMetadata(StringRef Kind,
1377 SmallVectorImpl<MDNode *> &MDs) const {
1378 if (hasMetadata())
1379 getMetadata(getContext().getMDKindID(Kind), MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001380}
1381
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001382void GlobalObject::addMetadata(unsigned KindID, MDNode &MD) {
1383 if (!hasMetadata())
1384 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001385
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001386 getContext().pImpl->GlobalObjectMetadata[this].insert(KindID, MD);
1387}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001388
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001389void GlobalObject::addMetadata(StringRef Kind, MDNode &MD) {
1390 addMetadata(getContext().getMDKindID(Kind), MD);
1391}
1392
1393void GlobalObject::eraseMetadata(unsigned KindID) {
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001394 // Nothing to unset.
1395 if (!hasMetadata())
1396 return;
1397
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001398 auto &Store = getContext().pImpl->GlobalObjectMetadata[this];
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001399 Store.erase(KindID);
1400 if (Store.empty())
1401 clearMetadata();
1402}
1403
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001404void GlobalObject::getAllMetadata(
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001405 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1406 MDs.clear();
1407
1408 if (!hasMetadata())
1409 return;
1410
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001411 getContext().pImpl->GlobalObjectMetadata[this].getAll(MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001412}
1413
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001414void GlobalObject::clearMetadata() {
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001415 if (!hasMetadata())
1416 return;
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001417 getContext().pImpl->GlobalObjectMetadata.erase(this);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001418 setHasMetadataHashEntry(false);
1419}
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001420
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001421void GlobalObject::setMetadata(unsigned KindID, MDNode *N) {
1422 eraseMetadata(KindID);
1423 if (N)
1424 addMetadata(KindID, *N);
1425}
1426
1427void GlobalObject::setMetadata(StringRef Kind, MDNode *N) {
1428 setMetadata(getContext().getMDKindID(Kind), N);
1429}
1430
1431MDNode *GlobalObject::getMetadata(unsigned KindID) const {
1432 SmallVector<MDNode *, 1> MDs;
1433 getMetadata(KindID, MDs);
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001434 if (MDs.empty())
1435 return nullptr;
1436 return MDs[0];
1437}
1438
1439MDNode *GlobalObject::getMetadata(StringRef Kind) const {
1440 return getMetadata(getContext().getMDKindID(Kind));
1441}
1442
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001443void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +00001444 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1445 Other->getAllMetadata(MDs);
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001446 for (auto &MD : MDs) {
1447 // We need to adjust the type metadata offset.
1448 if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1449 auto *OffsetConst = cast<ConstantInt>(
1450 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1451 Metadata *TypeId = MD.second->getOperand(1);
1452 auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1453 OffsetConst->getType(), OffsetConst->getValue() + Offset));
1454 addMetadata(LLVMContext::MD_type,
1455 *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1456 continue;
1457 }
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001458 // If an offset adjustment was specified we need to modify the DIExpression
1459 // to prepend the adjustment:
1460 // !DIExpression(DW_OP_plus, Offset, [original expr])
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001461 auto *Attachment = MD.second;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001462 if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001463 DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
1464 DIExpression *E = nullptr;
1465 if (!GV) {
1466 auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1467 GV = GVE->getVariable();
1468 E = GVE->getExpression();
1469 }
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001470 ArrayRef<uint64_t> OrigElements;
1471 if (E)
1472 OrigElements = E->getElements();
1473 std::vector<uint64_t> Elements(OrigElements.size() + 2);
Florian Hahnffc498d2017-06-14 13:14:38 +00001474 Elements[0] = dwarf::DW_OP_plus_uconst;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001475 Elements[1] = Offset;
1476 std::copy(OrigElements.begin(), OrigElements.end(), Elements.begin() + 2);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001477 E = DIExpression::get(getContext(), Elements);
1478 Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001479 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001480 addMetadata(MD.first, *Attachment);
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001481 }
1482}
1483
1484void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
1485 addMetadata(
1486 LLVMContext::MD_type,
1487 *MDTuple::get(getContext(),
Eugene Zelenkode6cce22017-06-19 22:05:08 +00001488 {ConstantAsMetadata::get(ConstantInt::get(
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001489 Type::getInt64Ty(getContext()), Offset)),
1490 TypeID}));
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +00001491}
1492
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001493void Function::setSubprogram(DISubprogram *SP) {
1494 setMetadata(LLVMContext::MD_dbg, SP);
1495}
1496
1497DISubprogram *Function::getSubprogram() const {
1498 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1499}
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001500
Dehao Chenfb02f712017-02-10 21:09:07 +00001501bool Function::isDebugInfoForProfiling() const {
1502 if (DISubprogram *SP = getSubprogram()) {
1503 if (DICompileUnit *CU = SP->getUnit()) {
1504 return CU->getDebugInfoForProfiling();
1505 }
1506 }
1507 return false;
1508}
1509
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001510void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001511 addMetadata(LLVMContext::MD_dbg, *GV);
1512}
1513
1514void GlobalVariable::getDebugInfo(
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001515 SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001516 SmallVector<MDNode *, 1> MDs;
1517 getMetadata(LLVMContext::MD_dbg, MDs);
1518 for (MDNode *MD : MDs)
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001519 GVs.push_back(cast<DIGlobalVariableExpression>(MD));
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001520}