LLVM  8.0.1
Metadata.cpp
Go to the documentation of this file.
1 //===- Metadata.cpp - Implement Metadata classes --------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Metadata classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "LLVMContextImpl.h"
15 #include "MetadataImpl.h"
17 #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"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/IR/Argument.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/ConstantRange.h"
34 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalObject.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/Metadata.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/TrackingMDRef.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/IR/Value.h"
47 #include "llvm/IR/ValueHandle.h"
48 #include "llvm/Support/Casting.h"
51 #include <algorithm>
52 #include <cassert>
53 #include <cstddef>
54 #include <cstdint>
55 #include <iterator>
56 #include <tuple>
57 #include <type_traits>
58 #include <utility>
59 #include <vector>
60 
61 using namespace llvm;
62 
63 MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
64  : Value(Ty, MetadataAsValueVal), MD(MD) {
65  track();
66 }
67 
69  getType()->getContext().pImpl->MetadataAsValues.erase(MD);
70  untrack();
71 }
72 
73 /// Canonicalize metadata arguments to intrinsics.
74 ///
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.
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 
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 
115  Metadata *MD) {
116  MD = canonicalizeMetadataForValue(Context, MD);
117  auto &Store = Context.pImpl->MetadataAsValues;
118  return Store.lookup(MD);
119 }
120 
121 void 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 
144 void MetadataAsValue::track() {
145  if (MD)
146  MetadataTracking::track(&MD, *MD, *this);
147 }
148 
149 void MetadataAsValue::untrack() {
150  if (MD)
152 }
153 
154 bool 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");
158  if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
159  R->addRef(Ref, Owner);
160  return true;
161  }
162  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  }
168  return false;
169 }
170 
172  assert(Ref && "Expected live reference");
173  if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
174  R->dropRef(Ref);
175  else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
176  PH->Use = nullptr;
177 }
178 
179 bool 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");
183  if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
184  R->moveRef(Ref, New, MD);
185  return true;
186  }
187  assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
188  "Unexpected move of an MDOperand");
189  assert(!isReplaceable(MD) &&
190  "Expected un-replaceable metadata, since we didn't move a reference");
191  return false;
192 }
193 
195  return ReplaceableMetadataImpl::isReplaceable(MD);
196 }
197 
198 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
199  bool WasInserted =
200  UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
201  .second;
202  (void)WasInserted;
203  assert(WasInserted && "Expected to add a reference");
204 
205  ++NextIndex;
206  assert(NextIndex != 0 && "Unexpected overflow");
207 }
208 
209 void ReplaceableMetadataImpl::dropRef(void *Ref) {
210  bool WasErased = UseMap.erase(Ref);
211  (void)WasErased;
212  assert(WasErased && "Expected to drop a reference");
213 }
214 
215 void 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");
219  auto OwnerAndIndex = I->second;
220  UseMap.erase(I);
221  bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
222  (void)WasInserted;
223  assert(WasInserted && "Expected to add a reference");
224 
225  // Check that the references are direct if there's no owner.
226  (void)MD;
227  assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
228  "Reference without owner must be direct");
229  assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
230  "Reference without owner must be direct");
231 }
232 
234  if (UseMap.empty())
235  return;
236 
237  // Copy out uses since UseMap will get touched below.
238  using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
239  SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
240  llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
241  return L.second.second < R.second.second;
242  });
243  for (const auto &Pair : Uses) {
244  // Check that this Ref hasn't disappeared after RAUW (when updating a
245  // previous Ref).
246  if (!UseMap.count(Pair.first))
247  continue;
248 
249  OwnerTy Owner = Pair.second.first;
250  if (!Owner) {
251  // Update unowned tracking references directly.
252  Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
253  Ref = MD;
254  if (MD)
256  UseMap.erase(Pair.first);
257  continue;
258  }
259 
260  // Check for MetadataAsValue.
261  if (Owner.is<MetadataAsValue *>()) {
262  Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
263  continue;
264  }
265 
266  // There's a Metadata owner -- dispatch.
267  Metadata *OwnerMD = Owner.get<Metadata *>();
268  switch (OwnerMD->getMetadataID()) {
269 #define HANDLE_METADATA_LEAF(CLASS) \
270  case Metadata::CLASS##Kind: \
271  cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
272  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 
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.
291  using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
292  SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
293  llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
294  return L.second.second < R.second.second;
295  });
296  UseMap.clear();
297  for (const auto &Pair : Uses) {
298  auto Owner = Pair.second.first;
299  if (!Owner)
300  continue;
301  if (Owner.is<MetadataAsValue *>())
302  continue;
303 
304  // Resolve MDNodes that point at this.
305  auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
306  if (!OwnerMD)
307  continue;
308  if (OwnerMD->isResolved())
309  continue;
310  OwnerMD->decrementUnresolvedOperandCount();
311  }
312 }
313 
314 ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
315  if (auto *N = dyn_cast<MDNode>(&MD))
316  return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
317  return dyn_cast<ValueAsMetadata>(&MD);
318 }
319 
320 ReplaceableMetadataImpl *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 
326 bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
327  if (auto *N = dyn_cast<MDNode>(&MD))
328  return !N->isResolved();
329  return dyn_cast<ValueAsMetadata>(&MD);
330 }
331 
333  assert(V && "Expected value");
334  if (auto *A = dyn_cast<Argument>(V)) {
335  if (auto *Fn = A->getParent())
336  return Fn->getSubprogram();
337  return nullptr;
338  }
339 
340  if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {
341  if (auto *Fn = BB->getParent())
342  return Fn->getSubprogram();
343  return nullptr;
344  }
345 
346  return nullptr;
347 }
348 
350  assert(V && "Unexpected null Value");
351 
352  auto &Context = V->getContext();
353  auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
354  if (!Entry) {
355  assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
356  "Expected constant or function-local value");
357  assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
358  V->IsUsedByMD = true;
359  if (auto *C = dyn_cast<Constant>(V))
360  Entry = new ConstantAsMetadata(C);
361  else
362  Entry = new LocalAsMetadata(V);
363  }
364 
365  return Entry;
366 }
367 
369  assert(V && "Unexpected null Value");
370  return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
371 }
372 
374  assert(V && "Expected valid value");
375 
376  auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
377  auto I = Store.find(V);
378  if (I == Store.end())
379  return;
380 
381  // Remove old entry from the map.
382  ValueAsMetadata *MD = I->second;
383  assert(MD && "Expected valid metadata");
384  assert(MD->getValue() == V && "Expected valid mapping");
385  Store.erase(I);
386 
387  // Delete the metadata.
388  MD->replaceAllUsesWith(nullptr);
389  delete MD;
390 }
391 
393  assert(From && "Expected valid value");
394  assert(To && "Expected valid value");
395  assert(From != To && "Expected changed value");
396  assert(From->getType() == To->getType() && "Unexpected type change");
397 
398  LLVMContext &Context = From->getType()->getContext();
399  auto &Store = Context.pImpl->ValuesAsMetadata;
400  auto I = Store.find(From);
401  if (I == Store.end()) {
402  assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
403  return;
404  }
405 
406  // Remove old entry from the map.
407  assert(From->IsUsedByMD && "Expected From to be used by metadata");
408  From->IsUsedByMD = false;
409  ValueAsMetadata *MD = I->second;
410  assert(MD && "Expected valid metadata");
411  assert(MD->getValue() == From && "Expected valid mapping");
412  Store.erase(I);
413 
414  if (isa<LocalAsMetadata>(MD)) {
415  if (auto *C = dyn_cast<Constant>(To)) {
416  // Local became a constant.
418  delete MD;
419  return;
420  }
423  // DISubprogram changed.
424  MD->replaceAllUsesWith(nullptr);
425  delete MD;
426  return;
427  }
428  } else if (!isa<Constant>(To)) {
429  // Changed to function-local value.
430  MD->replaceAllUsesWith(nullptr);
431  delete MD;
432  return;
433  }
434 
435  auto *&Entry = Store[To];
436  if (Entry) {
437  // The target already exists.
438  MD->replaceAllUsesWith(Entry);
439  delete MD;
440  return;
441  }
442 
443  // Update MD in place (and update the map entry).
444  assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
445  To->IsUsedByMD = true;
446  MD->V = To;
447  Entry = MD;
448 }
449 
450 //===----------------------------------------------------------------------===//
451 // MDString implementation.
452 //
453 
455  auto &Store = Context.pImpl->MDStringCache;
456  auto I = Store.try_emplace(Str);
457  auto &MapEntry = I.first->getValue();
458  if (!I.second)
459  return &MapEntry;
460  MapEntry.Entry = &*I.first;
461  return &MapEntry;
462 }
463 
465  assert(Entry && "Expected to find string map entry");
466  return Entry->first();
467 }
468 
469 //===----------------------------------------------------------------------===//
470 // MDNode implementation.
471 //
472 
473 // Assert that the MDNode types will not be unaligned by the objects
474 // prepended to them.
475 #define HANDLE_MDNODE_LEAF(CLASS) \
476  static_assert( \
477  alignof(uint64_t) >= alignof(CLASS), \
478  "Alignment is insufficient after objects prepended to " #CLASS);
479 #include "llvm/IR/Metadata.def"
480 
481 void *MDNode::operator new(size_t Size, unsigned NumOps) {
482  size_t OpSize = NumOps * sizeof(MDOperand);
483  // uint64_t is the most aligned type we need support (ensured by static_assert
484  // above)
485  OpSize = alignTo(OpSize, alignof(uint64_t));
486  void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
487  MDOperand *O = static_cast<MDOperand *>(Ptr);
488  for (MDOperand *E = O - NumOps; O != E; --O)
489  (void)new (O - 1) MDOperand;
490  return Ptr;
491 }
492 
493 void MDNode::operator delete(void *Mem) {
494  MDNode *N = static_cast<MDNode *>(Mem);
495  size_t OpSize = N->NumOperands * sizeof(MDOperand);
496  OpSize = alignTo(OpSize, alignof(uint64_t));
497 
498  MDOperand *O = static_cast<MDOperand *>(Mem);
499  for (MDOperand *E = O - N->NumOperands; O != E; --O)
500  (O - 1)->~MDOperand();
501  ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
502 }
503 
504 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
506  : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
507  NumUnresolved(0), Context(Context) {
508  unsigned Op = 0;
509  for (Metadata *MD : Ops1)
510  setOperand(Op++, MD);
511  for (Metadata *MD : Ops2)
512  setOperand(Op++, MD);
513 
514  if (!isUniqued())
515  return;
516 
517  // Count the unresolved operands. If there are any, RAUW support will be
518  // added lazily on first reference.
519  countUnresolvedOperands();
520 }
521 
522 TempMDNode MDNode::clone() const {
523  switch (getMetadataID()) {
524  default:
525  llvm_unreachable("Invalid MDNode subclass");
526 #define HANDLE_MDNODE_LEAF(CLASS) \
527  case CLASS##Kind: \
528  return cast<CLASS>(this)->cloneImpl();
529 #include "llvm/IR/Metadata.def"
530  }
531 }
532 
534  if (auto *N = dyn_cast_or_null<MDNode>(Op))
535  return !N->isResolved();
536  return false;
537 }
538 
539 void MDNode::countUnresolvedOperands() {
540  assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
541  assert(isUniqued() && "Expected this to be uniqued");
542  NumUnresolved = count_if(operands(), isOperandUnresolved);
543 }
544 
545 void MDNode::makeUniqued() {
546  assert(isTemporary() && "Expected this to be temporary");
547  assert(!isResolved() && "Expected this to be unresolved");
548 
549  // Enable uniquing callbacks.
550  for (auto &Op : mutable_operands())
551  Op.reset(Op.get(), this);
552 
553  // Make this 'uniqued'.
554  Storage = Uniqued;
555  countUnresolvedOperands();
556  if (!NumUnresolved) {
557  dropReplaceableUses();
558  assert(isResolved() && "Expected this to be resolved");
559  }
560 
561  assert(isUniqued() && "Expected this to be uniqued");
562 }
563 
564 void MDNode::makeDistinct() {
565  assert(isTemporary() && "Expected this to be temporary");
566  assert(!isResolved() && "Expected this to be unresolved");
567 
568  // Drop RAUW support and store as a distinct node.
569  dropReplaceableUses();
571 
572  assert(isDistinct() && "Expected this to be distinct");
573  assert(isResolved() && "Expected this to be resolved");
574 }
575 
577  assert(isUniqued() && "Expected this to be uniqued");
578  assert(!isResolved() && "Expected this to be unresolved");
579 
580  NumUnresolved = 0;
581  dropReplaceableUses();
582 
583  assert(isResolved() && "Expected this to be resolved");
584 }
585 
586 void MDNode::dropReplaceableUses() {
587  assert(!NumUnresolved && "Unexpected unresolved operand");
588 
589  // Drop any RAUW support.
590  if (Context.hasReplaceableUses())
591  Context.takeReplaceableUses()->resolveAllUses();
592 }
593 
594 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
595  assert(isUniqued() && "Expected this to be uniqued");
596  assert(NumUnresolved != 0 && "Expected unresolved operands");
597 
598  // Check if an operand was resolved.
599  if (!isOperandUnresolved(Old)) {
600  if (isOperandUnresolved(New))
601  // An operand was un-resolved!
602  ++NumUnresolved;
603  } else if (!isOperandUnresolved(New))
604  decrementUnresolvedOperandCount();
605 }
606 
607 void MDNode::decrementUnresolvedOperandCount() {
608  assert(!isResolved() && "Expected this to be unresolved");
609  if (isTemporary())
610  return;
611 
612  assert(isUniqued() && "Expected this to be uniqued");
613  if (--NumUnresolved)
614  return;
615 
616  // Last unresolved operand has just been resolved.
617  dropReplaceableUses();
618  assert(isResolved() && "Expected this to become resolved");
619 }
620 
622  if (isResolved())
623  return;
624 
625  // Resolve this node immediately.
626  resolve();
627 
628  // Resolve all operands.
629  for (const auto &Op : operands()) {
630  auto *N = dyn_cast_or_null<MDNode>(Op);
631  if (!N)
632  continue;
633 
634  assert(!N->isTemporary() &&
635  "Expected all forward declarations to be resolved");
636  if (!N->isResolved())
637  N->resolveCycles();
638  }
639 }
640 
641 static bool hasSelfReference(MDNode *N) {
642  for (Metadata *MD : N->operands())
643  if (MD == N)
644  return true;
645  return false;
646 }
647 
648 MDNode *MDNode::replaceWithPermanentImpl() {
649  switch (getMetadataID()) {
650  default:
651  // If this type isn't uniquable, replace with a distinct node.
652  return replaceWithDistinctImpl();
653 
654 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
655  case CLASS##Kind: \
656  break;
657 #include "llvm/IR/Metadata.def"
658  }
659 
660  // Even if this type is uniquable, self-references have to be distinct.
661  if (hasSelfReference(this))
662  return replaceWithDistinctImpl();
663  return replaceWithUniquedImpl();
664 }
665 
666 MDNode *MDNode::replaceWithUniquedImpl() {
667  // Try to uniquify in place.
668  MDNode *UniquedNode = uniquify();
669 
670  if (UniquedNode == this) {
671  makeUniqued();
672  return this;
673  }
674 
675  // Collision, so RAUW instead.
676  replaceAllUsesWith(UniquedNode);
677  deleteAsSubclass();
678  return UniquedNode;
679 }
680 
681 MDNode *MDNode::replaceWithDistinctImpl() {
682  makeDistinct();
683  return this;
684 }
685 
686 void MDTuple::recalculateHash() {
687  setHash(MDTupleInfo::KeyTy::calculateHash(this));
688 }
689 
691  for (unsigned I = 0, E = NumOperands; I != E; ++I)
692  setOperand(I, nullptr);
693  if (Context.hasReplaceableUses()) {
694  Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
695  (void)Context.takeReplaceableUses();
696  }
697 }
698 
699 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
700  unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
701  assert(Op < getNumOperands() && "Expected valid operand");
702 
703  if (!isUniqued()) {
704  // This node is not uniqued. Just set the operand and be done with it.
705  setOperand(Op, New);
706  return;
707  }
708 
709  // This node is uniqued.
710  eraseFromStore();
711 
712  Metadata *Old = getOperand(Op);
713  setOperand(Op, New);
714 
715  // Drop uniquing for self-reference cycles and deleted constants.
716  if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
717  if (!isResolved())
718  resolve();
720  return;
721  }
722 
723  // Re-unique the node.
724  auto *Uniqued = uniquify();
725  if (Uniqued == this) {
726  if (!isResolved())
727  resolveAfterOperandChange(Old, New);
728  return;
729  }
730 
731  // Collision.
732  if (!isResolved()) {
733  // Still unresolved, so RAUW.
734  //
735  // First, clear out all operands to prevent any recursion (similar to
736  // dropAllReferences(), but we still need the use-list).
737  for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
738  setOperand(O, nullptr);
739  if (Context.hasReplaceableUses())
741  deleteAsSubclass();
742  return;
743  }
744 
745  // Store in non-uniqued form if RAUW isn't possible.
747 }
748 
749 void MDNode::deleteAsSubclass() {
750  switch (getMetadataID()) {
751  default:
752  llvm_unreachable("Invalid subclass of MDNode");
753 #define HANDLE_MDNODE_LEAF(CLASS) \
754  case CLASS##Kind: \
755  delete cast<CLASS>(this); \
756  break;
757 #include "llvm/IR/Metadata.def"
758  }
759 }
760 
761 template <class T, class InfoT>
763  if (T *U = getUniqued(Store, N))
764  return U;
765 
766  Store.insert(N);
767  return N;
768 }
769 
770 template <class NodeTy> struct MDNode::HasCachedHash {
771  using Yes = char[1];
772  using No = char[2];
773  template <class U, U Val> struct SFINAE {};
774 
775  template <class U>
776  static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
777  template <class U> static No &check(...);
778 
779  static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
780 };
781 
782 MDNode *MDNode::uniquify() {
783  assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
784 
785  // Try to insert into uniquing store.
786  switch (getMetadataID()) {
787  default:
788  llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
789 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
790  case CLASS##Kind: { \
791  CLASS *SubclassThis = cast<CLASS>(this); \
792  std::integral_constant<bool, HasCachedHash<CLASS>::value> \
793  ShouldRecalculateHash; \
794  dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
795  return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
796  }
797 #include "llvm/IR/Metadata.def"
798  }
799 }
800 
801 void MDNode::eraseFromStore() {
802  switch (getMetadataID()) {
803  default:
804  llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
805 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
806  case CLASS##Kind: \
807  getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
808  break;
809 #include "llvm/IR/Metadata.def"
810  }
811 }
812 
813 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
814  StorageType Storage, bool ShouldCreate) {
815  unsigned Hash = 0;
816  if (Storage == Uniqued) {
817  MDTupleInfo::KeyTy Key(MDs);
818  if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
819  return N;
820  if (!ShouldCreate)
821  return nullptr;
822  Hash = Key.getHash();
823  } else {
824  assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
825  }
826 
827  return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
828  Storage, Context.pImpl->MDTuples);
829 }
830 
832  assert(N->isTemporary() && "Expected temporary node");
833  N->replaceAllUsesWith(nullptr);
834  N->deleteAsSubclass();
835 }
836 
838  assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
839  assert(!NumUnresolved && "Unexpected unresolved nodes");
840  Storage = Distinct;
841  assert(isResolved() && "Expected this to be resolved");
842 
843  // Reset the hash.
844  switch (getMetadataID()) {
845  default:
846  llvm_unreachable("Invalid subclass of MDNode");
847 #define HANDLE_MDNODE_LEAF(CLASS) \
848  case CLASS##Kind: { \
849  std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
850  dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
851  break; \
852  }
853 #include "llvm/IR/Metadata.def"
854  }
855 
856  getContext().pImpl->DistinctMDNodes.push_back(this);
857 }
858 
859 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
860  if (getOperand(I) == New)
861  return;
862 
863  if (!isUniqued()) {
864  setOperand(I, New);
865  return;
866  }
867 
868  handleChangedOperand(mutable_begin() + I, New);
869 }
870 
871 void MDNode::setOperand(unsigned I, Metadata *New) {
872  assert(I < NumOperands);
873  mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
874 }
875 
876 /// Get a node or a self-reference that looks like it.
877 ///
878 /// Special handling for finding self-references, for use by \a
879 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
880 /// when self-referencing nodes were still uniqued. If the first operand has
881 /// the same operands as \c Ops, return the first operand instead.
883  ArrayRef<Metadata *> Ops) {
884  if (!Ops.empty())
885  if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
886  if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
887  for (unsigned I = 1, E = Ops.size(); I != E; ++I)
888  if (Ops[I] != N->getOperand(I))
889  return MDNode::get(Context, Ops);
890  return N;
891  }
892 
893  return MDNode::get(Context, Ops);
894 }
895 
897  if (!A)
898  return B;
899  if (!B)
900  return A;
901 
903  MDs.insert(B->op_begin(), B->op_end());
904 
905  // FIXME: This preserves long-standing behaviour, but is it really the right
906  // behaviour? Or was that an unintended side-effect of node uniquing?
907  return getOrSelfReference(A->getContext(), MDs.getArrayRef());
908 }
909 
911  if (!A || !B)
912  return nullptr;
913 
915  SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
916  MDs.remove_if([&](Metadata *MD) { return !is_contained(BSet, MD); });
917 
918  // FIXME: This preserves long-standing behaviour, but is it really the right
919  // behaviour? Or was that an unintended side-effect of node uniquing?
920  return getOrSelfReference(A->getContext(), MDs.getArrayRef());
921 }
922 
924  if (!A || !B)
925  return nullptr;
926 
927  return concatenate(A, B);
928 }
929 
931  if (!A || !B)
932  return nullptr;
933 
934  APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
935  APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
936  if (AVal.compare(BVal) == APFloat::cmpLessThan)
937  return A;
938  return B;
939 }
940 
941 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
942  return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
943 }
944 
945 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
946  return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
947 }
948 
950  ConstantInt *Low, ConstantInt *High) {
951  ConstantRange NewRange(Low->getValue(), High->getValue());
952  unsigned Size = EndPoints.size();
953  APInt LB = EndPoints[Size - 2]->getValue();
954  APInt LE = EndPoints[Size - 1]->getValue();
955  ConstantRange LastRange(LB, LE);
956  if (canBeMerged(NewRange, LastRange)) {
957  ConstantRange Union = LastRange.unionWith(NewRange);
958  Type *Ty = High->getType();
959  EndPoints[Size - 2] =
960  cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
961  EndPoints[Size - 1] =
962  cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
963  return true;
964  }
965  return false;
966 }
967 
969  ConstantInt *Low, ConstantInt *High) {
970  if (!EndPoints.empty())
971  if (tryMergeRange(EndPoints, Low, High))
972  return;
973 
974  EndPoints.push_back(Low);
975  EndPoints.push_back(High);
976 }
977 
979  // Given two ranges, we want to compute the union of the ranges. This
980  // is slightly complicated by having to combine the intervals and merge
981  // the ones that overlap.
982 
983  if (!A || !B)
984  return nullptr;
985 
986  if (A == B)
987  return A;
988 
989  // First, walk both lists in order of the lower boundary of each interval.
990  // At each step, try to merge the new interval to the last one we adedd.
992  int AI = 0;
993  int BI = 0;
994  int AN = A->getNumOperands() / 2;
995  int BN = B->getNumOperands() / 2;
996  while (AI < AN && BI < BN) {
997  ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
998  ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
999 
1000  if (ALow->getValue().slt(BLow->getValue())) {
1001  addRange(EndPoints, ALow,
1002  mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1003  ++AI;
1004  } else {
1005  addRange(EndPoints, BLow,
1006  mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1007  ++BI;
1008  }
1009  }
1010  while (AI < AN) {
1011  addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1012  mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1013  ++AI;
1014  }
1015  while (BI < BN) {
1016  addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1017  mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1018  ++BI;
1019  }
1020 
1021  // If we have more than 2 ranges (4 endpoints) we have to try to merge
1022  // the last and first ones.
1023  unsigned Size = EndPoints.size();
1024  if (Size > 4) {
1025  ConstantInt *FB = EndPoints[0];
1026  ConstantInt *FE = EndPoints[1];
1027  if (tryMergeRange(EndPoints, FB, FE)) {
1028  for (unsigned i = 0; i < Size - 2; ++i) {
1029  EndPoints[i] = EndPoints[i + 2];
1030  }
1031  EndPoints.resize(Size - 2);
1032  }
1033  }
1034 
1035  // If in the end we have a single range, it is possible that it is now the
1036  // full range. Just drop the metadata in that case.
1037  if (EndPoints.size() == 2) {
1038  ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
1039  if (Range.isFullSet())
1040  return nullptr;
1041  }
1042 
1044  MDs.reserve(EndPoints.size());
1045  for (auto *I : EndPoints)
1047  return MDNode::get(A->getContext(), MDs);
1048 }
1049 
1051  if (!A || !B)
1052  return nullptr;
1053 
1054  ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1055  ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1056  if (AVal->getZExtValue() < BVal->getZExtValue())
1057  return A;
1058  return B;
1059 }
1060 
1061 //===----------------------------------------------------------------------===//
1062 // NamedMDNode implementation.
1063 //
1064 
1065 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1066  return *(SmallVector<TrackingMDRef, 4> *)Operands;
1067 }
1068 
1069 NamedMDNode::NamedMDNode(const Twine &N)
1070  : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
1071 
1074  delete &getNMDOps(Operands);
1075 }
1076 
1078  return (unsigned)getNMDOps(Operands).size();
1079 }
1080 
1081 MDNode *NamedMDNode::getOperand(unsigned i) const {
1082  assert(i < getNumOperands() && "Invalid Operand number!");
1083  auto *N = getNMDOps(Operands)[i].get();
1084  return cast_or_null<MDNode>(N);
1085 }
1086 
1087 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1088 
1089 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1090  assert(I < getNumOperands() && "Invalid operand number");
1091  getNMDOps(Operands)[I].reset(New);
1092 }
1093 
1094 void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
1095 
1096 void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
1097 
1099 
1100 //===----------------------------------------------------------------------===//
1101 // Instruction Metadata method implementations.
1102 //
1103 void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1104  for (auto &I : Attachments)
1105  if (I.first == ID) {
1106  I.second.reset(&MD);
1107  return;
1108  }
1109  Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1110  std::make_tuple(&MD));
1111 }
1112 
1113 bool MDAttachmentMap::erase(unsigned ID) {
1114  if (empty())
1115  return false;
1116 
1117  // Common case is one/last value.
1118  if (Attachments.back().first == ID) {
1119  Attachments.pop_back();
1120  return true;
1121  }
1122 
1123  for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1124  ++I)
1125  if (I->first == ID) {
1126  *I = std::move(Attachments.back());
1127  Attachments.pop_back();
1128  return true;
1129  }
1130 
1131  return false;
1132 }
1133 
1135  for (const auto &I : Attachments)
1136  if (I.first == ID)
1137  return I.second;
1138  return nullptr;
1139 }
1140 
1142  SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1143  Result.append(Attachments.begin(), Attachments.end());
1144 
1145  // Sort the resulting array so it is stable.
1146  if (Result.size() > 1)
1147  array_pod_sort(Result.begin(), Result.end());
1148 }
1149 
1151  Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1152 }
1153 
1155  for (const auto &A : Attachments)
1156  if (A.MDKind == ID)
1157  return A.Node;
1158  return nullptr;
1159 }
1160 
1162  SmallVectorImpl<MDNode *> &Result) const {
1163  for (const auto &A : Attachments)
1164  if (A.MDKind == ID)
1165  Result.push_back(A.Node);
1166 }
1167 
1169  auto I = std::remove_if(Attachments.begin(), Attachments.end(),
1170  [ID](const Attachment &A) { return A.MDKind == ID; });
1171  bool Changed = I != Attachments.end();
1172  Attachments.erase(I, Attachments.end());
1173  return Changed;
1174 }
1175 
1177  SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1178  for (const auto &A : Attachments)
1179  Result.emplace_back(A.MDKind, A.Node);
1180 
1181  // Sort the resulting array so it is stable with respect to metadata IDs. We
1182  // need to preserve the original insertion order though.
1183  std::stable_sort(
1184  Result.begin(), Result.end(),
1185  [](const std::pair<unsigned, MDNode *> &A,
1186  const std::pair<unsigned, MDNode *> &B) { return A.first < B.first; });
1187 }
1188 
1190  if (!Node && !hasMetadata())
1191  return;
1192  setMetadata(getContext().getMDKindID(Kind), Node);
1193 }
1194 
1195 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1196  return getMetadataImpl(getContext().getMDKindID(Kind));
1197 }
1198 
1200  if (!hasMetadataHashEntry())
1201  return; // Nothing to remove!
1202 
1203  auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
1204 
1205  SmallSet<unsigned, 4> KnownSet;
1206  KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1207  if (KnownSet.empty()) {
1208  // Just drop our entry at the store.
1209  InstructionMetadata.erase(this);
1210  setHasMetadataHashEntry(false);
1211  return;
1212  }
1213 
1214  auto &Info = InstructionMetadata[this];
1215  Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1216  return !KnownSet.count(I.first);
1217  });
1218 
1219  if (Info.empty()) {
1220  // Drop our entry at the store.
1221  InstructionMetadata.erase(this);
1222  setHasMetadataHashEntry(false);
1223  }
1224 }
1225 
1226 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1227  if (!Node && !hasMetadata())
1228  return;
1229 
1230  // Handle 'dbg' as a special case since it is not stored in the hash table.
1231  if (KindID == LLVMContext::MD_dbg) {
1232  DbgLoc = DebugLoc(Node);
1233  return;
1234  }
1235 
1236  // Handle the case when we're adding/updating metadata on an instruction.
1237  if (Node) {
1238  auto &Info = getContext().pImpl->InstructionMetadata[this];
1239  assert(!Info.empty() == hasMetadataHashEntry() &&
1240  "HasMetadata bit is wonked");
1241  if (Info.empty())
1242  setHasMetadataHashEntry(true);
1243  Info.set(KindID, *Node);
1244  return;
1245  }
1246 
1247  // Otherwise, we're removing metadata from an instruction.
1248  assert((hasMetadataHashEntry() ==
1249  (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
1250  "HasMetadata bit out of date!");
1251  if (!hasMetadataHashEntry())
1252  return; // Nothing to remove!
1253  auto &Info = getContext().pImpl->InstructionMetadata[this];
1254 
1255  // Handle removal of an existing value.
1256  Info.erase(KindID);
1257 
1258  if (!Info.empty())
1259  return;
1260 
1261  getContext().pImpl->InstructionMetadata.erase(this);
1262  setHasMetadataHashEntry(false);
1263 }
1264 
1269 }
1270 
1271 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
1272  // Handle 'dbg' as a special case since it is not stored in the hash table.
1273  if (KindID == LLVMContext::MD_dbg)
1274  return DbgLoc.getAsMDNode();
1275 
1276  if (!hasMetadataHashEntry())
1277  return nullptr;
1278  auto &Info = getContext().pImpl->InstructionMetadata[this];
1279  assert(!Info.empty() && "bit out of sync with hash table");
1280 
1281  return Info.lookup(KindID);
1282 }
1283 
1284 void Instruction::getAllMetadataImpl(
1285  SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1286  Result.clear();
1287 
1288  // Handle 'dbg' as a special case since it is not stored in the hash table.
1289  if (DbgLoc) {
1290  Result.push_back(
1291  std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1292  if (!hasMetadataHashEntry())
1293  return;
1294  }
1295 
1296  assert(hasMetadataHashEntry() &&
1297  getContext().pImpl->InstructionMetadata.count(this) &&
1298  "Shouldn't have called this");
1299  const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1300  assert(!Info.empty() && "Shouldn't have called this");
1301  Info.getAll(Result);
1302 }
1303 
1304 void Instruction::getAllMetadataOtherThanDebugLocImpl(
1305  SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1306  Result.clear();
1307  assert(hasMetadataHashEntry() &&
1308  getContext().pImpl->InstructionMetadata.count(this) &&
1309  "Shouldn't have called this");
1310  const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
1311  assert(!Info.empty() && "Shouldn't have called this");
1312  Info.getAll(Result);
1313 }
1314 
1315 bool Instruction::extractProfMetadata(uint64_t &TrueVal,
1316  uint64_t &FalseVal) const {
1317  assert(
1318  (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
1319  "Looking for branch weights on something besides branch or select");
1320 
1321  auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1322  if (!ProfileData || ProfileData->getNumOperands() != 3)
1323  return false;
1324 
1325  auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1326  if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1327  return false;
1328 
1329  auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
1330  auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
1331  if (!CITrue || !CIFalse)
1332  return false;
1333 
1334  TrueVal = CITrue->getValue().getZExtValue();
1335  FalseVal = CIFalse->getValue().getZExtValue();
1336 
1337  return true;
1338 }
1339 
1340 bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
1341  assert((getOpcode() == Instruction::Br ||
1344  getOpcode() == Instruction::Invoke ||
1345  getOpcode() == Instruction::Switch) &&
1346  "Looking for branch weights on something besides branch");
1347 
1348  TotalVal = 0;
1349  auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1350  if (!ProfileData)
1351  return false;
1352 
1353  auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1354  if (!ProfDataName)
1355  return false;
1356 
1357  if (ProfDataName->getString().equals("branch_weights")) {
1358  TotalVal = 0;
1359  for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
1360  auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
1361  if (!V)
1362  return false;
1363  TotalVal += V->getValue().getZExtValue();
1364  }
1365  return true;
1366  } else if (ProfDataName->getString().equals("VP") &&
1367  ProfileData->getNumOperands() > 3) {
1368  TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
1369  ->getValue()
1370  .getZExtValue();
1371  return true;
1372  }
1373  return false;
1374 }
1375 
1376 void Instruction::clearMetadataHashEntries() {
1377  assert(hasMetadataHashEntry() && "Caller should check");
1378  getContext().pImpl->InstructionMetadata.erase(this);
1379  setHasMetadataHashEntry(false);
1380 }
1381 
1382 void GlobalObject::getMetadata(unsigned KindID,
1383  SmallVectorImpl<MDNode *> &MDs) const {
1384  if (hasMetadata())
1385  getContext().pImpl->GlobalObjectMetadata[this].get(KindID, MDs);
1386 }
1387 
1389  SmallVectorImpl<MDNode *> &MDs) const {
1390  if (hasMetadata())
1391  getMetadata(getContext().getMDKindID(Kind), MDs);
1392 }
1393 
1394 void GlobalObject::addMetadata(unsigned KindID, MDNode &MD) {
1395  if (!hasMetadata())
1396  setHasMetadataHashEntry(true);
1397 
1398  getContext().pImpl->GlobalObjectMetadata[this].insert(KindID, MD);
1399 }
1400 
1402  addMetadata(getContext().getMDKindID(Kind), MD);
1403 }
1404 
1405 bool GlobalObject::eraseMetadata(unsigned KindID) {
1406  // Nothing to unset.
1407  if (!hasMetadata())
1408  return false;
1409 
1410  auto &Store = getContext().pImpl->GlobalObjectMetadata[this];
1411  bool Changed = Store.erase(KindID);
1412  if (Store.empty())
1413  clearMetadata();
1414  return Changed;
1415 }
1416 
1418  SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1419  MDs.clear();
1420 
1421  if (!hasMetadata())
1422  return;
1423 
1424  getContext().pImpl->GlobalObjectMetadata[this].getAll(MDs);
1425 }
1426 
1428  if (!hasMetadata())
1429  return;
1430  getContext().pImpl->GlobalObjectMetadata.erase(this);
1431  setHasMetadataHashEntry(false);
1432 }
1433 
1434 void GlobalObject::setMetadata(unsigned KindID, MDNode *N) {
1435  eraseMetadata(KindID);
1436  if (N)
1437  addMetadata(KindID, *N);
1438 }
1439 
1441  setMetadata(getContext().getMDKindID(Kind), N);
1442 }
1443 
1444 MDNode *GlobalObject::getMetadata(unsigned KindID) const {
1445  if (hasMetadata())
1446  return getContext().pImpl->GlobalObjectMetadata[this].lookup(KindID);
1447  return nullptr;
1448 }
1449 
1451  return getMetadata(getContext().getMDKindID(Kind));
1452 }
1453 
1454 void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
1456  Other->getAllMetadata(MDs);
1457  for (auto &MD : MDs) {
1458  // We need to adjust the type metadata offset.
1459  if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1460  auto *OffsetConst = cast<ConstantInt>(
1461  cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1462  Metadata *TypeId = MD.second->getOperand(1);
1463  auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1464  OffsetConst->getType(), OffsetConst->getValue() + Offset));
1465  addMetadata(LLVMContext::MD_type,
1466  *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1467  continue;
1468  }
1469  // If an offset adjustment was specified we need to modify the DIExpression
1470  // to prepend the adjustment:
1471  // !DIExpression(DW_OP_plus, Offset, [original expr])
1472  auto *Attachment = MD.second;
1473  if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
1474  DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
1475  DIExpression *E = nullptr;
1476  if (!GV) {
1477  auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1478  GV = GVE->getVariable();
1479  E = GVE->getExpression();
1480  }
1481  ArrayRef<uint64_t> OrigElements;
1482  if (E)
1483  OrigElements = E->getElements();
1484  std::vector<uint64_t> Elements(OrigElements.size() + 2);
1485  Elements[0] = dwarf::DW_OP_plus_uconst;
1486  Elements[1] = Offset;
1487  llvm::copy(OrigElements, Elements.begin() + 2);
1488  E = DIExpression::get(getContext(), Elements);
1489  Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
1490  }
1491  addMetadata(MD.first, *Attachment);
1492  }
1493 }
1494 
1496  addMetadata(
1500  Type::getInt64Ty(getContext()), Offset)),
1501  TypeID}));
1502 }
1503 
1506 }
1507 
1509  return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1510 }
1511 
1513  if (DISubprogram *SP = getSubprogram()) {
1514  if (DICompileUnit *CU = SP->getUnit()) {
1515  return CU->getDebugInfoForProfiling();
1516  }
1517  }
1518  return false;
1519 }
1520 
1522  addMetadata(LLVMContext::MD_dbg, *GV);
1523 }
1524 
1528  getMetadata(LLVMContext::MD_dbg, MDs);
1529  for (MDNode *MD : MDs)
1530  GVs.push_back(cast<DIGlobalVariableExpression>(MD));
1531 }
uint64_t CallInst * C
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
Definition: Constants.h:172
static void deleteTemporary(MDNode *N)
Deallocate a node created by getTemporary.
Definition: Metadata.cpp:831
bool isUniqued() const
Definition: Metadata.h:942
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:711
unsigned char Storage
Storage flag for non-uniqued, otherwise unowned, metadata.
Definition: Metadata.h:69
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1133
bool isDistinct() const
Definition: Metadata.h:943
StringMap< MDString, BumpPtrAllocator > MDStringCache
LLVMContext & Context
ConstantRange unionWith(const ConstantRange &CR) const
Return the range that results from the union of this range with another range.
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition: Metadata.h:661
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1081
This class represents lattice values for constants.
Definition: AllocatorList.h:24
const APInt & getUpper() const
Return the upper value for this range.
MDNode * TBAA
The tag for type-based alias analysis.
Definition: Metadata.h:658
iterator begin() const
Definition: ArrayRef.h:137
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
Definition: Metadata.cpp:859
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:454
void clearOperands()
Drop all references to this node&#39;s operands.
Definition: Metadata.cpp:1096
Implements a dense probed hash-table based set.
Definition: DenseSet.h:250
std::unique_ptr< ReplaceableMetadataImpl > takeReplaceableUses()
Drop RAUW support.
Definition: Metadata.h:830
DenseMap< Value *, ValueAsMetadata * > ValuesAsMetadata
static MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
Definition: Metadata.cpp:923
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1204
void addOperand(MDNode *M)
Definition: Metadata.cpp:1087
This file contains the declarations for metadata subclasses.
void storeDistinctInContext()
Definition: Metadata.cpp:837
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition: STLExtras.h:1260
void dropAllReferences()
Definition: Metadata.cpp:690
Shared implementation of use-lists for replaceable metadata.
Definition: Metadata.h:279
A debug info location.
Definition: DebugLoc.h:34
Metadata node.
Definition: Metadata.h:864
static bool canBeMerged(const ConstantRange &A, const ConstantRange &B)
Definition: Metadata.cpp:945
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1069
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:685
static T * storeImpl(T *N, StorageType Storage, StoreT &Store)
Definition: MetadataImpl.h:43
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
void setOperand(unsigned I, Metadata *New)
Set an operand.
Definition: Metadata.cpp:871
static Type * getMetadataTy(LLVMContext &C)
Definition: Type.cpp:166
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
Definition: Metadata.cpp:1417
void reserve(size_type N)
Definition: SmallVector.h:376
void setOperand(unsigned I, MDNode *New)
Definition: Metadata.cpp:1089
op_iterator op_end() const
Definition: Metadata.h:1063
uint64_t High
Tuple of metadata.
Definition: Metadata.h:1106
TempMDNode clone() const
Create a (temporary) clone of this.
Definition: Metadata.cpp:522
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:130
void set(unsigned ID, MDNode &MD)
Set an attachment to a particular node.
Definition: Metadata.cpp:1103
TypedTrackingMDRef< MDNode > TrackingMDNodeRef
void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
Definition: Metadata.cpp:1454
DenseMap< const Instruction *, MDAttachmentMap > InstructionMetadata
Collection of per-instruction metadata used in this context.
LLVM_NODISCARD bool empty() const
Definition: SmallSet.h:156
amdgpu Simplify well known AMD library false Value Value const Twine & Name
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
bool isResolved() const
Check if node is fully resolved.
Definition: Metadata.h:940
void eraseFromParent()
Drop all references and remove the node from parent module.
Definition: Metadata.cpp:1094
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:197
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
static bool track(Metadata *&MD)
Track the reference to metadata.
Definition: Metadata.h:221
The access may reference the value stored in memory.
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1444
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:55
unsigned getNumOperands() const
Definition: Metadata.cpp:1077
std::vector< MDNode * > DistinctMDNodes
This file implements a class to represent arbitrary precision integral constant values and operations...
void resolveCycles()
Resolve cycles.
Definition: Metadata.cpp:621
op_iterator op_begin() const
Definition: Metadata.h:1059
static Metadata * canonicalizeMetadataForValue(LLVMContext &Context, Metadata *MD)
Canonicalize metadata arguments to intrinsics.
Definition: Metadata.cpp:84
Subprogram description.
Key
PAL metadata keys.
static void handleRAUW(Value *From, Value *To)
Definition: Metadata.cpp:392
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
static SmallVector< TrackingMDRef, 4 > & getNMDOps(void *Operands)
Definition: Metadata.cpp:1065
void dropUnknownNonDebugMetadata()
Definition: Instruction.h:276
op_range operands() const
Definition: Metadata.h:1067
LLVMContext & getContext() const
Definition: Metadata.h:924
unsigned getMetadataID() const
Definition: Metadata.h:100
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:138
static MDNode * intersect(MDNode *A, MDNode *B)
Definition: Metadata.cpp:910
static T * uniquifyImpl(T *N, DenseSet< T *, InfoT > &Store)
Definition: Metadata.cpp:762
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
Definition: Metadata.cpp:1340
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:339
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition: Metadata.h:949
MDNode * lookup(unsigned ID) const
Get a particular attachment (if any).
Definition: Metadata.cpp:1134
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:410
Analysis containing CSE Info
Definition: CSEInfo.cpp:21
void resolve()
Resolve a unique, unresolved node.
Definition: Metadata.cpp:576
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:106
StringRef getString() const
Definition: Metadata.cpp:464
MDNode * lookup(unsigned ID) const
Returns the first attachment with the given ID or nullptr if no such attachment exists.
Definition: Metadata.cpp:1154
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1166
bool isDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
Definition: Metadata.cpp:1512
static MDNode * getMostGenericRange(MDNode *A, MDNode *B)
Definition: Metadata.cpp:978
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
Definition: Metadata.cpp:1504
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition: STLExtras.h:1083
static T * getUniqued(DenseSet< T *, InfoT > &Store, const typename InfoT::KeyTy &Key)
Definition: MetadataImpl.h:23
void resolveAllUses(bool ResolveUsers=true)
Resolve all uses of this.
Definition: Metadata.cpp:281
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:149
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void addTypeMetadata(unsigned Offset, Metadata *TypeID)
Definition: Metadata.cpp:1495
static ValueAsMetadata * getIfExists(Value *V)
Definition: Metadata.cpp:368
static MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:114
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1265
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1508
static MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1050
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static bool isContiguous(const ConstantRange &A, const ConstantRange &B)
Definition: Metadata.cpp:941
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression *> &GVs) const
Fill the vector with all debug info attachements.
Definition: Metadata.cpp:1525
StorageType
Active type of storage.
Definition: Metadata.h:66
A pair of DIGlobalVariable and DIExpression.
void getAll(SmallVectorImpl< std::pair< unsigned, MDNode *>> &Result) const
Appends all attachments for the global to Result, sorting by attachment ID.
Definition: Metadata.cpp:1176
This file declares a class to represent arbitrary precision floating point values and provide a varie...
static bool retrack(Metadata *&MD, Metadata *&New)
Move tracking from one reference to another.
Definition: Metadata.h:257
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type. ...
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:181
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:174
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1226
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&... Args)
Definition: DIBuilder.cpp:746
size_t size() const
Definition: SmallVector.h:53
static wasm::ValType getType(const TargetRegisterClass *RC)
C setMetadata(LLVMContext::MD_range, MDNode::get(Context, LowAndHigh))
Value * getValue() const
Definition: Metadata.h:379
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1226
mutable_op_range mutable_operands()
Definition: Metadata.h:898
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:71
static bool isOperandUnresolved(Metadata *Op)
Definition: Metadata.cpp:533
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1116
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:210
bool isEmptySet() const
Return true if this set contains no members.
DenseMap< Metadata *, MetadataAsValue * > MetadataAsValues
bool hasReplaceableUses() const
Whether this contains RAUW support.
Definition: Metadata.h:791
DenseMap< const GlobalObject *, MDGlobalAttachmentMap > GlobalObjectMetadata
Collection of per-GlobalObject metadata used in this context.
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:298
bool erase(unsigned ID)
Definition: Metadata.cpp:1168
static MDNode * getOrSelfReference(LLVMContext &Context, ArrayRef< Metadata *> Ops)
Get a node or a self-reference that looks like it.
Definition: Metadata.cpp:882
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1167
BlockVerifier::State From
unsigned IsUsedByMD
Definition: Value.h:118
MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata *> Ops1, ArrayRef< Metadata *> Ops2=None)
Definition: Metadata.cpp:504
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:349
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
This class represents a range of values.
Definition: ConstantRange.h:47
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1394
iterator end() const
Definition: ArrayRef.h:138
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:644
MDNode * NoAlias
The tag specifying the noalias scope.
Definition: Metadata.h:664
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:622
void reset()
Definition: Metadata.h:727
DWARF expression.
void get(unsigned ID, SmallVectorImpl< MDNode *> &Result) const
Appends all attachments with the given ID to Result in insertion order.
Definition: Metadata.cpp:1161
static void untrack(Metadata *&MD)
Stop tracking a reference to metadata.
Definition: Metadata.h:246
Class for arbitrary precision integers.
Definition: APInt.h:70
void insert(unsigned ID, MDNode &MD)
Definition: Metadata.cpp:1150
StringRef getName() const
Definition: Metadata.cpp:1098
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1434
MDOperand * mutable_begin()
Definition: Metadata.h:893
void getAll(SmallVectorImpl< std::pair< unsigned, MDNode *>> &Result) const
Copy out all the attachments.
Definition: Metadata.cpp:1141
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
void replaceAllUsesWith(Metadata *MD)
Handle collisions after Value::replaceAllUsesWith().
Definition: Metadata.h:392
static MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
Definition: Metadata.cpp:896
const APInt & getLower() const
Return the lower value for this range.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
uint32_t Size
Definition: Profile.cpp:47
void replaceAllUsesWith(Metadata *MD)
Replace all uses of this with MD.
Definition: Metadata.cpp:233
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:18
static void addRange(SmallVectorImpl< ConstantInt *> &EndPoints, ConstantInt *Low, ConstantInt *High)
Definition: Metadata.cpp:968
static bool hasSelfReference(MDNode *N)
Definition: Metadata.cpp:641
const unsigned Kind
T get() const
Returns the value of the specified pointer type.
Definition: PointerUnion.h:135
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void handleDeletion(Value *V)
Definition: Metadata.cpp:373
LLVM Value Representation.
Definition: Value.h:73
bool erase(unsigned ID)
Remove an attachment.
Definition: Metadata.cpp:1113
static const Function * getParent(const Value *V)
bool isTemporary() const
Definition: Metadata.h:944
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Definition: Metadata.cpp:1521
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A single uniqued string.
Definition: Metadata.h:604
int is() const
Test if the Union currently holds the type matching T.
Definition: PointerUnion.h:123
bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
Definition: Metadata.cpp:1405
static bool isReplaceable(const Metadata &MD)
Check whether metadata is replaceable.
Definition: Metadata.cpp:194
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1075
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
Definition: Metadata.cpp:1315
static bool tryMergeRange(SmallVectorImpl< ConstantInt *> &EndPoints, ConstantInt *Low, ConstantInt *High)
Definition: Metadata.cpp:949
static MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
Definition: Metadata.cpp:930
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1238
ReplaceableMetadataImpl * getReplaceableUses() const
Definition: Metadata.h:801
Root of the metadata hierarchy.
Definition: Metadata.h:58
static DISubprogram * getLocalFunctionMetadata(Value *V)
Definition: Metadata.cpp:332
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
cmpResult compare(const APFloat &RHS) const
Definition: APFloat.h:1102
A discriminated union of two pointer types, with the discriminator in the low bit of the pointer...
Definition: PointerUnion.h:87
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:165
void resize(size_type N)
Definition: SmallVector.h:351
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:1245