blob: 6227c209352c78e477376aa2c6eb6194599482ee [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"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.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/SmallString.h"
22#include "llvm/ADT/StringMap.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000024#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Instruction.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Module.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000028#include "llvm/IR/ValueHandle.h"
Duncan P. N. Exon Smith46d91ad2014-11-14 18:42:06 +000029
Devang Patela4f43fb2009-07-28 21:49:47 +000030using namespace llvm;
31
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000032MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
33 : Value(Ty, MetadataAsValueVal), MD(MD) {
34 track();
35}
36
37MetadataAsValue::~MetadataAsValue() {
38 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
39 untrack();
40}
41
42/// \brief Canonicalize metadata arguments to intrinsics.
43///
44/// To support bitcode upgrades (and assembly semantic sugar) for \a
45/// MetadataAsValue, we need to canonicalize certain metadata.
46///
47/// - nullptr is replaced by an empty MDNode.
48/// - An MDNode with a single null operand is replaced by an empty MDNode.
49/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
50///
51/// This maintains readability of bitcode from when metadata was a type of
52/// value, and these bridges were unnecessary.
53static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
54 Metadata *MD) {
55 if (!MD)
56 // !{}
57 return MDNode::get(Context, None);
58
59 // Return early if this isn't a single-operand MDNode.
60 auto *N = dyn_cast<MDNode>(MD);
61 if (!N || N->getNumOperands() != 1)
62 return MD;
63
64 if (!N->getOperand(0))
65 // !{}
66 return MDNode::get(Context, None);
67
68 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
69 // Look through the MDNode.
70 return C;
71
72 return MD;
73}
74
75MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
76 MD = canonicalizeMetadataForValue(Context, MD);
77 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
78 if (!Entry)
79 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
80 return Entry;
81}
82
83MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
84 Metadata *MD) {
85 MD = canonicalizeMetadataForValue(Context, MD);
86 auto &Store = Context.pImpl->MetadataAsValues;
87 auto I = Store.find(MD);
88 return I == Store.end() ? nullptr : I->second;
89}
90
91void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
92 LLVMContext &Context = getContext();
93 MD = canonicalizeMetadataForValue(Context, MD);
94 auto &Store = Context.pImpl->MetadataAsValues;
95
96 // Stop tracking the old metadata.
97 Store.erase(this->MD);
98 untrack();
99 this->MD = nullptr;
100
101 // Start tracking MD, or RAUW if necessary.
102 auto *&Entry = Store[MD];
103 if (Entry) {
104 replaceAllUsesWith(Entry);
105 delete this;
106 return;
107 }
108
109 this->MD = MD;
110 track();
111 Entry = this;
112}
113
114void MetadataAsValue::track() {
115 if (MD)
116 MetadataTracking::track(&MD, *MD, *this);
117}
118
119void MetadataAsValue::untrack() {
120 if (MD)
121 MetadataTracking::untrack(MD);
122}
123
124void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000125 bool WasInserted =
126 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
127 .second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000128 (void)WasInserted;
129 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000130
131 ++NextIndex;
132 assert(NextIndex != 0 && "Unexpected overflow");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000133}
134
135void ReplaceableMetadataImpl::dropRef(void *Ref) {
136 bool WasErased = UseMap.erase(Ref);
137 (void)WasErased;
138 assert(WasErased && "Expected to drop a reference");
139}
140
141void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
142 const Metadata &MD) {
143 auto I = UseMap.find(Ref);
144 assert(I != UseMap.end() && "Expected to move a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000145 auto OwnerAndIndex = I->second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000146 UseMap.erase(I);
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000147 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
148 (void)WasInserted;
149 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000150
151 // Check that the references are direct if there's no owner.
152 (void)MD;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000153 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000154 "Reference without owner must be direct");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000155 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000156 "Reference without owner must be direct");
157}
158
159void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000160 assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
161 "Expected non-temp node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000162
163 if (UseMap.empty())
164 return;
165
166 // Copy out uses since UseMap will get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000167 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
168 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
169 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
170 return L.second.second < R.second.second;
171 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000172 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith4a4f7852015-01-14 19:56:10 +0000173 // Check that this Ref hasn't disappeared after RAUW (when updating a
174 // previous Ref).
175 if (!UseMap.count(Pair.first))
176 continue;
177
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000178 OwnerTy Owner = Pair.second.first;
179 if (!Owner) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000180 // Update unowned tracking references directly.
181 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
182 Ref = MD;
Duncan P. N. Exon Smith121eeff2014-12-12 19:24:33 +0000183 if (MD)
184 MetadataTracking::track(Ref);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000185 UseMap.erase(Pair.first);
186 continue;
187 }
188
189 // Check for MetadataAsValue.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000190 if (Owner.is<MetadataAsValue *>()) {
191 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000192 continue;
193 }
194
195 // There's a Metadata owner -- dispatch.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000196 Metadata *OwnerMD = Owner.get<Metadata *>();
197 switch (OwnerMD->getMetadataID()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000198#define HANDLE_METADATA_LEAF(CLASS) \
199 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000200 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000201 continue;
202#include "llvm/IR/Metadata.def"
203 default:
204 llvm_unreachable("Invalid metadata subclass");
205 }
206 }
207 assert(UseMap.empty() && "Expected all uses to be replaced");
208}
209
210void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
211 if (UseMap.empty())
212 return;
213
214 if (!ResolveUsers) {
215 UseMap.clear();
216 return;
217 }
218
219 // Copy out uses since UseMap could get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000220 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
221 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
222 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
223 return L.second.second < R.second.second;
224 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000225 UseMap.clear();
226 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000227 auto Owner = Pair.second.first;
228 if (!Owner)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000229 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000230 if (Owner.is<MetadataAsValue *>())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000231 continue;
232
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000233 // Resolve MDNodes that point at this.
234 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000235 if (!OwnerMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000236 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000237 if (OwnerMD->isResolved())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000238 continue;
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000239 OwnerMD->decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000240 }
241}
242
243static Function *getLocalFunction(Value *V) {
244 assert(V && "Expected value");
245 if (auto *A = dyn_cast<Argument>(V))
246 return A->getParent();
247 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
248 return BB->getParent();
249 return nullptr;
250}
251
252ValueAsMetadata *ValueAsMetadata::get(Value *V) {
253 assert(V && "Unexpected null Value");
254
255 auto &Context = V->getContext();
256 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
257 if (!Entry) {
258 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
259 "Expected constant or function-local value");
260 assert(!V->NameAndIsUsedByMD.getInt() &&
261 "Expected this to be the only metadata use");
262 V->NameAndIsUsedByMD.setInt(true);
263 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000264 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000265 else
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000266 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000267 }
268
269 return Entry;
270}
271
272ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
273 assert(V && "Unexpected null Value");
274 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
275}
276
277void ValueAsMetadata::handleDeletion(Value *V) {
278 assert(V && "Expected valid value");
279
280 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
281 auto I = Store.find(V);
282 if (I == Store.end())
283 return;
284
285 // Remove old entry from the map.
286 ValueAsMetadata *MD = I->second;
287 assert(MD && "Expected valid metadata");
288 assert(MD->getValue() == V && "Expected valid mapping");
289 Store.erase(I);
290
291 // Delete the metadata.
292 MD->replaceAllUsesWith(nullptr);
293 delete MD;
294}
295
296void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
297 assert(From && "Expected valid value");
298 assert(To && "Expected valid value");
299 assert(From != To && "Expected changed value");
300 assert(From->getType() == To->getType() && "Unexpected type change");
301
302 LLVMContext &Context = From->getType()->getContext();
303 auto &Store = Context.pImpl->ValuesAsMetadata;
304 auto I = Store.find(From);
305 if (I == Store.end()) {
306 assert(!From->NameAndIsUsedByMD.getInt() &&
307 "Expected From not to be used by metadata");
308 return;
309 }
310
311 // Remove old entry from the map.
312 assert(From->NameAndIsUsedByMD.getInt() &&
313 "Expected From to be used by metadata");
314 From->NameAndIsUsedByMD.setInt(false);
315 ValueAsMetadata *MD = I->second;
316 assert(MD && "Expected valid metadata");
317 assert(MD->getValue() == From && "Expected valid mapping");
318 Store.erase(I);
319
320 if (isa<LocalAsMetadata>(MD)) {
321 if (auto *C = dyn_cast<Constant>(To)) {
322 // Local became a constant.
323 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
324 delete MD;
325 return;
326 }
327 if (getLocalFunction(From) && getLocalFunction(To) &&
328 getLocalFunction(From) != getLocalFunction(To)) {
329 // Function changed.
330 MD->replaceAllUsesWith(nullptr);
331 delete MD;
332 return;
333 }
334 } else if (!isa<Constant>(To)) {
335 // Changed to function-local value.
336 MD->replaceAllUsesWith(nullptr);
337 delete MD;
338 return;
339 }
340
341 auto *&Entry = Store[To];
342 if (Entry) {
343 // The target already exists.
344 MD->replaceAllUsesWith(Entry);
345 delete MD;
346 return;
347 }
348
349 // Update MD in place (and update the map entry).
350 assert(!To->NameAndIsUsedByMD.getInt() &&
351 "Expected this to be the only metadata use");
352 To->NameAndIsUsedByMD.setInt(true);
353 MD->V = To;
354 Entry = MD;
355}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000356
Devang Patela4f43fb2009-07-28 21:49:47 +0000357//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000358// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000359//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000360
Devang Pateldcb99d32009-10-22 00:10:15 +0000361MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000362 auto &Store = Context.pImpl->MDStringCache;
363 auto I = Store.find(Str);
364 if (I != Store.end())
365 return &I->second;
366
Duncan P. N. Exon Smith56228312014-12-09 18:52:38 +0000367 auto *Entry =
368 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000369 bool WasInserted = Store.insert(Entry);
370 (void)WasInserted;
371 assert(WasInserted && "Expected entry to be inserted");
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000372 Entry->second.Entry = Entry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000373 return &Entry->second;
374}
375
376StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000377 assert(Entry && "Expected to find string map entry");
378 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000379}
380
381//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000382// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000383//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000384
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000385void *MDNode::operator new(size_t Size, unsigned NumOps) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000386 void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000387 MDOperand *O = static_cast<MDOperand *>(Ptr);
388 for (MDOperand *E = O + NumOps; O != E; ++O)
389 (void)new (O) MDOperand;
390 return O;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000391}
392
393void MDNode::operator delete(void *Mem) {
394 MDNode *N = static_cast<MDNode *>(Mem);
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000395 MDOperand *O = static_cast<MDOperand *>(Mem);
396 for (MDOperand *E = O - N->NumOperands; O != E; --O)
397 (O - 1)->~MDOperand();
398 ::operator delete(O);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000399}
400
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000401MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000402 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
403 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
404 NumUnresolved(0), Context(Context) {
405 unsigned Op = 0;
406 for (Metadata *MD : Ops1)
407 setOperand(Op++, MD);
408 for (Metadata *MD : Ops2)
409 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000410
Duncan P. N. Exon Smitha1ae4f62015-01-19 23:15:21 +0000411 if (isDistinct())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000412 return;
413
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000414 if (isUniqued())
415 // Check whether any operands are unresolved, requiring re-uniquing. If
416 // not, don't support RAUW.
417 if (!countUnresolvedOperands())
Duncan P. N. Exon Smitha1ae4f62015-01-19 23:15:21 +0000418 return;
419
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000420 this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
Devang Patela4f43fb2009-07-28 21:49:47 +0000421}
422
Duncan P. N. Exon Smith03e05832015-01-20 02:56:57 +0000423TempMDNode MDNode::clone() const {
424 switch (getMetadataID()) {
425 default:
426 llvm_unreachable("Invalid MDNode subclass");
427#define HANDLE_MDNODE_LEAF(CLASS) \
428 case CLASS##Kind: \
429 return cast<CLASS>(this)->cloneImpl();
430#include "llvm/IR/Metadata.def"
431 }
432}
433
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000434static bool isOperandUnresolved(Metadata *Op) {
435 if (auto *N = dyn_cast_or_null<MDNode>(Op))
436 return !N->isResolved();
437 return false;
438}
439
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000440unsigned MDNode::countUnresolvedOperands() {
441 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000442 for (const auto &Op : operands())
443 NumUnresolved += unsigned(isOperandUnresolved(Op));
444 return NumUnresolved;
445}
446
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000447void MDNode::makeUniqued() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000448 assert(isTemporary() && "Expected this to be temporary");
449 assert(!isResolved() && "Expected this to be unresolved");
450
451 // Make this 'uniqued'.
452 Storage = Uniqued;
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000453 if (!countUnresolvedOperands())
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000454 resolve();
455
456 assert(isUniqued() && "Expected this to be uniqued");
457}
458
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000459void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000460 assert(isTemporary() && "Expected this to be temporary");
461 assert(!isResolved() && "Expected this to be unresolved");
462
463 // Pretend to be uniqued, resolve the node, and then store in distinct table.
464 Storage = Uniqued;
465 resolve();
466 storeDistinctInContext();
467
468 assert(isDistinct() && "Expected this to be distinct");
469 assert(isResolved() && "Expected this to be resolved");
470}
471
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000472void MDNode::resolve() {
Duncan P. N. Exon Smithb8f79602015-01-19 19:26:24 +0000473 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000474 assert(!isResolved() && "Expected this to be unresolved");
475
476 // Move the map, so that this immediately looks resolved.
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000477 auto Uses = Context.takeReplaceableUses();
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000478 NumUnresolved = 0;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000479 assert(isResolved() && "Expected this to be resolved");
480
481 // Drop RAUW support.
482 Uses->resolveAllUses();
483}
484
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000485void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000486 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000487
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000488 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000489 if (!isOperandUnresolved(Old)) {
490 if (isOperandUnresolved(New))
491 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000492 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000493 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000494 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000495}
496
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000497void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000498 if (!--NumUnresolved)
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000499 // Last unresolved operand has just been resolved.
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000500 resolve();
501}
502
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000503void MDNode::resolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000504 if (isResolved())
505 return;
506
507 // Resolve this node immediately.
508 resolve();
509
510 // Resolve all operands.
511 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000512 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000513 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000514 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000515
516 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000517 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000518 if (!N->isResolved())
519 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000520 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000521}
522
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000523MDNode *MDNode::replaceWithUniquedImpl() {
524 // Try to uniquify in place.
525 MDNode *UniquedNode = uniquify();
526 if (UniquedNode == this) {
527 makeUniqued();
528 return this;
529 }
530
531 // Collision, so RAUW instead.
532 replaceAllUsesWith(UniquedNode);
533 deleteAsSubclass();
534 return UniquedNode;
535}
536
537MDNode *MDNode::replaceWithDistinctImpl() {
538 makeDistinct();
539 return this;
540}
541
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000542void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000543 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000544}
545
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000546void MDNode::dropAllReferences() {
547 for (unsigned I = 0, E = NumOperands; I != E; ++I)
548 setOperand(I, nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000549 if (!isResolved()) {
550 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
551 (void)Context.takeReplaceableUses();
552 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000553}
554
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000555void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000556 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
557 assert(Op < getNumOperands() && "Expected valid operand");
558
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000559 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000560 // This node is not uniqued. Just set the operand and be done with it.
561 setOperand(Op, New);
562 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000563 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000564
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000565 // This node is uniqued.
566 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000567
568 Metadata *Old = getOperand(Op);
569 setOperand(Op, New);
570
Duncan P. N. Exon Smithbcd960a2015-01-05 23:31:54 +0000571 // Drop uniquing for self-reference cycles.
572 if (New == this) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000573 if (!isResolved())
574 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000575 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000576 return;
577 }
578
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000579 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000580 auto *Uniqued = uniquify();
581 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000582 if (!isResolved())
583 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000584 return;
585 }
586
587 // Collision.
588 if (!isResolved()) {
589 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000590 //
591 // First, clear out all operands to prevent any recursion (similar to
592 // dropAllReferences(), but we still need the use-list).
593 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
594 setOperand(O, nullptr);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000595 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000596 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000597 return;
598 }
599
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000600 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000601 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000602}
603
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000604void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000605 switch (getMetadataID()) {
606 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000607 llvm_unreachable("Invalid subclass of MDNode");
608#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000609 case CLASS##Kind: \
610 delete cast<CLASS>(this); \
611 break;
612#include "llvm/IR/Metadata.def"
613 }
614}
615
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000616template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000617static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
618 if (T *U = getUniqued(Store, N))
619 return U;
620
621 Store.insert(N);
622 return N;
623}
624
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000625template <class NodeTy> struct MDNode::HasCachedHash {
626 typedef char Yes[1];
627 typedef char No[2];
628 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000629
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000630 template <class U>
631 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
632 template <class U> static No &check(...);
633
634 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
635};
636
637MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000638 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000639 switch (getMetadataID()) {
640 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000641 llvm_unreachable("Invalid subclass of MDNode");
642#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000643 case CLASS##Kind: { \
644 CLASS *SubclassThis = cast<CLASS>(this); \
645 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
646 ShouldRecalculateHash; \
647 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
648 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
649 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000650#include "llvm/IR/Metadata.def"
651 }
652}
653
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000654void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000655 switch (getMetadataID()) {
656 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000657 llvm_unreachable("Invalid subclass of MDNode");
658#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000659 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000660 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000661 break;
662#include "llvm/IR/Metadata.def"
663 }
664}
665
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000666MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000667 StorageType Storage, bool ShouldCreate) {
668 unsigned Hash = 0;
669 if (Storage == Uniqued) {
670 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000671 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
672 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000673 if (!ShouldCreate)
674 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000675 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000676 } else {
677 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
678 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000679
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000680 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
681 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000682}
683
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000684void MDNode::deleteTemporary(MDNode *N) {
685 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000686 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000687 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000688}
689
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000690void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000691 assert(isResolved() && "Expected resolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000692 Storage = Distinct;
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000693
694 // Reset the hash.
695 switch (getMetadataID()) {
696 default:
697 llvm_unreachable("Invalid subclass of MDNode");
698#define HANDLE_MDNODE_LEAF(CLASS) \
699 case CLASS##Kind: { \
700 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
701 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
702 break; \
703 }
704#include "llvm/IR/Metadata.def"
705 }
706
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +0000707 getContext().pImpl->DistinctMDNodes.insert(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000708}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000709
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000710void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
711 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000712 return;
Devang Patelf7188322009-09-03 01:39:20 +0000713
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000714 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000715 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000716 return;
717 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000718
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000719 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000720}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000721
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000722void MDNode::setOperand(unsigned I, Metadata *New) {
723 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000724 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000725}
726
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000727/// \brief Get a node, or a self-reference that looks like it.
728///
729/// Special handling for finding self-references, for use by \a
730/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
731/// when self-referencing nodes were still uniqued. If the first operand has
732/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000733static MDNode *getOrSelfReference(LLVMContext &Context,
734 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000735 if (!Ops.empty())
736 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
737 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
738 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
739 if (Ops[I] != N->getOperand(I))
740 return MDNode::get(Context, Ops);
741 return N;
742 }
743
744 return MDNode::get(Context, Ops);
745}
746
Hal Finkel94146652014-07-24 14:25:39 +0000747MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
748 if (!A)
749 return B;
750 if (!B)
751 return A;
752
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000753 SmallVector<Metadata *, 4> MDs(A->getNumOperands() + B->getNumOperands());
Hal Finkel94146652014-07-24 14:25:39 +0000754
755 unsigned j = 0;
756 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000757 MDs[j++] = A->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000758 for (unsigned i = 0, ie = B->getNumOperands(); i != ie; ++i)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000759 MDs[j++] = B->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000760
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000761 // FIXME: This preserves long-standing behaviour, but is it really the right
762 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000763 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000764}
765
766MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
767 if (!A || !B)
768 return nullptr;
769
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000770 SmallVector<Metadata *, 4> MDs;
Hal Finkel94146652014-07-24 14:25:39 +0000771 for (unsigned i = 0, ie = A->getNumOperands(); i != ie; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000772 Metadata *MD = A->getOperand(i);
Hal Finkel94146652014-07-24 14:25:39 +0000773 for (unsigned j = 0, je = B->getNumOperands(); j != je; ++j)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000774 if (MD == B->getOperand(j)) {
775 MDs.push_back(MD);
Hal Finkel94146652014-07-24 14:25:39 +0000776 break;
777 }
778 }
779
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000780 // FIXME: This preserves long-standing behaviour, but is it really the right
781 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000782 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000783}
784
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000785MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
786 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000787 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000788
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000789 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
790 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000791 if (AVal.compare(BVal) == APFloat::cmpLessThan)
792 return A;
793 return B;
794}
795
796static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
797 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
798}
799
800static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
801 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
802}
803
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000804static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
805 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000806 ConstantRange NewRange(Low->getValue(), High->getValue());
807 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000808 APInt LB = EndPoints[Size - 2]->getValue();
809 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000810 ConstantRange LastRange(LB, LE);
811 if (canBeMerged(NewRange, LastRange)) {
812 ConstantRange Union = LastRange.unionWith(NewRange);
813 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000814 EndPoints[Size - 2] =
815 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
816 EndPoints[Size - 1] =
817 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000818 return true;
819 }
820 return false;
821}
822
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000823static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
824 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000825 if (!EndPoints.empty())
826 if (tryMergeRange(EndPoints, Low, High))
827 return;
828
829 EndPoints.push_back(Low);
830 EndPoints.push_back(High);
831}
832
833MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
834 // Given two ranges, we want to compute the union of the ranges. This
835 // is slightly complitade by having to combine the intervals and merge
836 // the ones that overlap.
837
838 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000839 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000840
841 if (A == B)
842 return A;
843
844 // First, walk both lists in older of the lower boundary of each interval.
845 // 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 +0000846 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000847 int AI = 0;
848 int BI = 0;
849 int AN = A->getNumOperands() / 2;
850 int BN = B->getNumOperands() / 2;
851 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000852 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
853 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000854
855 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000856 addRange(EndPoints, ALow,
857 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000858 ++AI;
859 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000860 addRange(EndPoints, BLow,
861 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000862 ++BI;
863 }
864 }
865 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000866 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
867 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000868 ++AI;
869 }
870 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000871 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
872 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000873 ++BI;
874 }
875
876 // If we have more than 2 ranges (4 endpoints) we have to try to merge
877 // the last and first ones.
878 unsigned Size = EndPoints.size();
879 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000880 ConstantInt *FB = EndPoints[0];
881 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000882 if (tryMergeRange(EndPoints, FB, FE)) {
883 for (unsigned i = 0; i < Size - 2; ++i) {
884 EndPoints[i] = EndPoints[i + 2];
885 }
886 EndPoints.resize(Size - 2);
887 }
888 }
889
890 // If in the end we have a single range, it is possible that it is now the
891 // full range. Just drop the metadata in that case.
892 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000893 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000894 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +0000895 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000896 }
897
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000898 SmallVector<Metadata *, 4> MDs;
899 MDs.reserve(EndPoints.size());
900 for (auto *I : EndPoints)
901 MDs.push_back(ConstantAsMetadata::get(I));
902 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000903}
904
Devang Patel05a26fb2009-07-29 00:33:07 +0000905//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000906// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +0000907//
Devang Patel943ddf62010-01-12 18:34:06 +0000908
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000909static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
910 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +0000911}
912
Dan Gohman2637cc12010-07-21 23:38:33 +0000913NamedMDNode::NamedMDNode(const Twine &N)
Duncan P. N. Exon Smithc5754a62014-11-05 18:16:03 +0000914 : Name(N.str()), Parent(nullptr),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000915 Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +0000916
Chris Lattner1bc810b2009-12-28 08:07:14 +0000917NamedMDNode::~NamedMDNode() {
918 dropAllReferences();
919 delete &getNMDOps(Operands);
920}
921
Chris Lattner9b493022009-12-31 01:22:29 +0000922unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +0000923 return (unsigned)getNMDOps(Operands).size();
924}
925
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000926MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +0000927 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000928 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000929 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +0000930}
931
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000932void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +0000933
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +0000934void NamedMDNode::setOperand(unsigned I, MDNode *New) {
935 assert(I < getNumOperands() && "Invalid operand number");
936 getNMDOps(Operands)[I].reset(New);
937}
938
Devang Patel79238d72009-08-03 06:19:01 +0000939void NamedMDNode::eraseFromParent() {
Dan Gohman2637cc12010-07-21 23:38:33 +0000940 getParent()->eraseNamedMetadata(this);
Devang Patel79238d72009-08-03 06:19:01 +0000941}
942
Devang Patel79238d72009-08-03 06:19:01 +0000943void NamedMDNode::dropAllReferences() {
Chris Lattner1bc810b2009-12-28 08:07:14 +0000944 getNMDOps(Operands).clear();
Devang Patel79238d72009-08-03 06:19:01 +0000945}
946
Devang Patelfcfee0f2010-01-07 19:39:36 +0000947StringRef NamedMDNode::getName() const {
948 return StringRef(Name);
949}
Devang Pateld5497a4b2009-09-16 18:09:00 +0000950
951//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000952// Instruction Metadata method implementations.
953//
954
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000955void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
956 if (!Node && !hasMetadata())
957 return;
958 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000959}
960
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000961MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +0000962 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000963}
964
Rafael Espindolaab73c492014-01-28 16:56:46 +0000965void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
966 SmallSet<unsigned, 5> KnownSet;
967 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
968
969 // Drop debug if needed
970 if (KnownSet.erase(LLVMContext::MD_dbg))
971 DbgLoc = DebugLoc();
972
973 if (!hasMetadataHashEntry())
974 return; // Nothing to remove!
975
976 DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
977 getContext().pImpl->MetadataStore;
978
979 if (KnownSet.empty()) {
980 // Just drop our entry at the store.
981 MetadataStore.erase(this);
982 setHasMetadataHashEntry(false);
983 return;
984 }
985
986 LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
987 unsigned I;
988 unsigned E;
989 // Walk the array and drop any metadata we don't know.
990 for (I = 0, E = Info.size(); I != E;) {
991 if (KnownSet.count(Info[I].first)) {
992 ++I;
993 continue;
994 }
995
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000996 Info[I] = std::move(Info.back());
Rafael Espindolaab73c492014-01-28 16:56:46 +0000997 Info.pop_back();
998 --E;
999 }
1000 assert(E == Info.size());
1001
1002 if (E == 0) {
1003 // Drop our entry at the store.
1004 MetadataStore.erase(this);
1005 setHasMetadataHashEntry(false);
1006 }
1007}
1008
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001009/// setMetadata - Set the metadata of of the specified kind to the specified
1010/// node. This updates/replaces metadata if already present, or removes it if
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001011/// Node is null.
1012void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1013 if (!Node && !hasMetadata())
1014 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001015
Chris Lattnerc263b422010-03-30 23:03:27 +00001016 // Handle 'dbg' as a special case since it is not stored in the hash table.
1017 if (KindID == LLVMContext::MD_dbg) {
Chris Lattner593916d2010-04-02 20:21:22 +00001018 DbgLoc = DebugLoc::getFromDILocation(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001019 return;
1020 }
1021
Chris Lattnera0566972009-12-29 09:01:33 +00001022 // Handle the case when we're adding/updating metadata on an instruction.
1023 if (Node) {
1024 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001025 assert(!Info.empty() == hasMetadataHashEntry() &&
1026 "HasMetadata bit is wonked");
Chris Lattnera0566972009-12-29 09:01:33 +00001027 if (Info.empty()) {
Chris Lattnerc263b422010-03-30 23:03:27 +00001028 setHasMetadataHashEntry(true);
Chris Lattnera0566972009-12-29 09:01:33 +00001029 } else {
1030 // Handle replacement of an existing value.
Benjamin Kramer3ad5c962014-03-10 15:03:06 +00001031 for (auto &P : Info)
1032 if (P.first == KindID) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001033 P.second.reset(Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001034 return;
1035 }
1036 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001037
Chris Lattnera0566972009-12-29 09:01:33 +00001038 // No replacement, just add it to the list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001039 Info.emplace_back(std::piecewise_construct, std::make_tuple(KindID),
1040 std::make_tuple(Node));
Chris Lattnera0566972009-12-29 09:01:33 +00001041 return;
1042 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001043
Chris Lattnera0566972009-12-29 09:01:33 +00001044 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001045 assert((hasMetadataHashEntry() ==
Yaron Keren6d3194f2014-06-20 10:26:56 +00001046 (getContext().pImpl->MetadataStore.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001047 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001048 if (!hasMetadataHashEntry())
1049 return; // Nothing to remove!
Chris Lattnera0566972009-12-29 09:01:33 +00001050 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001051
Chris Lattnera0566972009-12-29 09:01:33 +00001052 // Common case is removing the only entry.
1053 if (Info.size() == 1 && Info[0].first == KindID) {
1054 getContext().pImpl->MetadataStore.erase(this);
Chris Lattnerc263b422010-03-30 23:03:27 +00001055 setHasMetadataHashEntry(false);
Chris Lattnera0566972009-12-29 09:01:33 +00001056 return;
1057 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001058
Chris Lattnerc263b422010-03-30 23:03:27 +00001059 // Handle removal of an existing value.
Chris Lattnera0566972009-12-29 09:01:33 +00001060 for (unsigned i = 0, e = Info.size(); i != e; ++i)
1061 if (Info[i].first == KindID) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001062 Info[i] = std::move(Info.back());
Chris Lattnera0566972009-12-29 09:01:33 +00001063 Info.pop_back();
1064 assert(!Info.empty() && "Removing last entry should be handled above");
1065 return;
1066 }
1067 // Otherwise, removing an entry that doesn't exist on the instruction.
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001068}
1069
Hal Finkelcc39b672014-07-24 12:16:19 +00001070void Instruction::setAAMetadata(const AAMDNodes &N) {
1071 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001072 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1073 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001074}
1075
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001076MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001077 // Handle 'dbg' as a special case since it is not stored in the hash table.
1078 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001079 return DbgLoc.getAsMDNode();
1080
Craig Topperc6207612014-04-09 06:08:46 +00001081 if (!hasMetadataHashEntry()) return nullptr;
Chris Lattnerc263b422010-03-30 23:03:27 +00001082
Chris Lattnera0566972009-12-29 09:01:33 +00001083 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001084 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001085
Benjamin Kramer3ad5c962014-03-10 15:03:06 +00001086 for (const auto &I : Info)
1087 if (I.first == KindID)
1088 return I.second;
Craig Topperc6207612014-04-09 06:08:46 +00001089 return nullptr;
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001090}
1091
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001092void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001093 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001094 Result.clear();
1095
1096 // Handle 'dbg' as a special case since it is not stored in the hash table.
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001097 if (!DbgLoc.isUnknown()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001098 Result.push_back(
1099 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Chris Lattnerc263b422010-03-30 23:03:27 +00001100 if (!hasMetadataHashEntry()) return;
1101 }
1102
1103 assert(hasMetadataHashEntry() &&
1104 getContext().pImpl->MetadataStore.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001105 "Shouldn't have called this");
1106 const LLVMContextImpl::MDMapTy &Info =
1107 getContext().pImpl->MetadataStore.find(this)->second;
1108 assert(!Info.empty() && "Shouldn't have called this");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001109
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001110 Result.reserve(Result.size() + Info.size());
1111 for (auto &I : Info)
1112 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001113
Chris Lattnera0566972009-12-29 09:01:33 +00001114 // Sort the resulting array so it is stable.
1115 if (Result.size() > 1)
1116 array_pod_sort(Result.begin(), Result.end());
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001117}
1118
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001119void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001120 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001121 Result.clear();
1122 assert(hasMetadataHashEntry() &&
1123 getContext().pImpl->MetadataStore.count(this) &&
1124 "Shouldn't have called this");
1125 const LLVMContextImpl::MDMapTy &Info =
Bill Wendlingdd91e732012-04-03 10:50:09 +00001126 getContext().pImpl->MetadataStore.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001127 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001128 Result.reserve(Result.size() + Info.size());
1129 for (auto &I : Info)
1130 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
Bill Wendlingdd91e732012-04-03 10:50:09 +00001131
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001132 // Sort the resulting array so it is stable.
1133 if (Result.size() > 1)
1134 array_pod_sort(Result.begin(), Result.end());
1135}
1136
Dan Gohman48a995f2010-07-20 22:25:04 +00001137/// clearMetadataHashEntries - Clear all hashtable-based metadata from
1138/// this instruction.
1139void Instruction::clearMetadataHashEntries() {
1140 assert(hasMetadataHashEntry() && "Caller should check");
1141 getContext().pImpl->MetadataStore.erase(this);
1142 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001143}