LLVM 22.0.0git
Metadata.cpp
Go to the documentation of this file.
1//===- Metadata.cpp - Implement Metadata classes --------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Metadata classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Metadata.h"
14#include "LLVMContextImpl.h"
15#include "MetadataImpl.h"
16#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/Twine.h"
28#include "llvm/IR/Argument.h"
29#include "llvm/IR/BasicBlock.h"
30#include "llvm/IR/Constant.h"
33#include "llvm/IR/Constants.h"
35#include "llvm/IR/DebugLoc.h"
37#include "llvm/IR/Function.h"
40#include "llvm/IR/Instruction.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/MDBuilder.h"
43#include "llvm/IR/Module.h"
46#include "llvm/IR/Type.h"
47#include "llvm/IR/Value.h"
51#include <cassert>
52#include <cstddef>
53#include <cstdint>
54#include <type_traits>
55#include <utility>
56#include <vector>
57
58using namespace llvm;
59
60MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
61 : Value(Ty, MetadataAsValueVal), MD(MD) {
62 track();
63}
64
67 untrack();
68}
69
70/// Canonicalize metadata arguments to intrinsics.
71///
72/// To support bitcode upgrades (and assembly semantic sugar) for \a
73/// MetadataAsValue, we need to canonicalize certain metadata.
74///
75/// - nullptr is replaced by an empty MDNode.
76/// - An MDNode with a single null operand is replaced by an empty MDNode.
77/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
78///
79/// This maintains readability of bitcode from when metadata was a type of
80/// value, and these bridges were unnecessary.
82 Metadata *MD) {
83 if (!MD)
84 // !{}
85 return MDNode::get(Context, {});
86
87 // Return early if this isn't a single-operand MDNode.
88 auto *N = dyn_cast<MDNode>(MD);
89 if (!N || N->getNumOperands() != 1)
90 return MD;
91
92 if (!N->getOperand(0))
93 // !{}
94 return MDNode::get(Context, {});
95
96 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
97 // Look through the MDNode.
98 return C;
99
100 return MD;
101}
102
105 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
106 if (!Entry)
108 return Entry;
109}
110
112 Metadata *MD) {
114 auto &Store = Context.pImpl->MetadataAsValues;
115 return Store.lookup(MD);
116}
117
118void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
120 MD = canonicalizeMetadataForValue(Context, MD);
121 auto &Store = Context.pImpl->MetadataAsValues;
122
123 // Stop tracking the old metadata.
124 Store.erase(this->MD);
125 untrack();
126 this->MD = nullptr;
127
128 // Start tracking MD, or RAUW if necessary.
129 auto *&Entry = Store[MD];
130 if (Entry) {
131 replaceAllUsesWith(Entry);
132 delete this;
133 return;
134 }
135
136 this->MD = MD;
137 track();
138 Entry = this;
139}
140
141void MetadataAsValue::track() {
142 if (MD)
143 MetadataTracking::track(&MD, *MD, *this);
144}
145
146void MetadataAsValue::untrack() {
147 if (MD)
149}
150
152 return static_cast<DbgVariableRecord *>(this);
153}
155 return static_cast<const DbgVariableRecord *>(this);
156}
157
159 // NOTE: We could inform the "owner" that a value has changed through
160 // getOwner, if needed.
161 auto OldMD = static_cast<Metadata **>(Old);
162 ptrdiff_t Idx = std::distance(&*DebugValues.begin(), OldMD);
163 // If replacing a ValueAsMetadata with a nullptr, replace it with a
164 // PoisonValue instead.
165 if (OldMD && isa<ValueAsMetadata>(*OldMD) && !New) {
166 auto *OldVAM = cast<ValueAsMetadata>(*OldMD);
167 New = ValueAsMetadata::get(PoisonValue::get(OldVAM->getValue()->getType()));
168 }
169 resetDebugValue(Idx, New);
170}
171
172void DebugValueUser::trackDebugValue(size_t Idx) {
173 assert(Idx < 3 && "Invalid debug value index.");
174 Metadata *&MD = DebugValues[Idx];
175 if (MD)
176 MetadataTracking::track(&MD, *MD, *this);
177}
178
179void DebugValueUser::trackDebugValues() {
180 for (Metadata *&MD : DebugValues)
181 if (MD)
182 MetadataTracking::track(&MD, *MD, *this);
183}
184
185void DebugValueUser::untrackDebugValue(size_t Idx) {
186 assert(Idx < 3 && "Invalid debug value index.");
187 Metadata *&MD = DebugValues[Idx];
188 if (MD)
190}
191
192void DebugValueUser::untrackDebugValues() {
193 for (Metadata *&MD : DebugValues)
194 if (MD)
196}
197
198void DebugValueUser::retrackDebugValues(DebugValueUser &X) {
199 assert(DebugValueUser::operator==(X) && "Expected values to match");
200 for (const auto &[MD, XMD] : zip(DebugValues, X.DebugValues))
201 if (XMD)
203 X.DebugValues.fill(nullptr);
204}
205
206bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
207 assert(Ref && "Expected live reference");
208 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
209 "Reference without owner must be direct");
210 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
211 R->addRef(Ref, Owner);
212 return true;
213 }
214 if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
215 assert(!PH->Use && "Placeholders can only be used once");
216 assert(!Owner && "Unexpected callback to owner");
217 PH->Use = static_cast<Metadata **>(Ref);
218 return true;
219 }
220 return false;
221}
222
224 assert(Ref && "Expected live reference");
225 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
226 R->dropRef(Ref);
227 else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
228 PH->Use = nullptr;
229}
230
231bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
232 assert(Ref && "Expected live reference");
233 assert(New && "Expected live reference");
234 assert(Ref != New && "Expected change");
235 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
236 R->moveRef(Ref, New, MD);
237 return true;
238 }
239 assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
240 "Unexpected move of an MDOperand");
241 assert(!isReplaceable(MD) &&
242 "Expected un-replaceable metadata, since we didn't move a reference");
243 return false;
244}
245
247 return ReplaceableMetadataImpl::isReplaceable(MD);
248}
249
252 for (auto Pair : UseMap) {
253 OwnerTy Owner = Pair.second.first;
254 if (Owner.isNull())
255 continue;
256 if (!isa<Metadata *>(Owner))
257 continue;
258 Metadata *OwnerMD = cast<Metadata *>(Owner);
259 if (OwnerMD->getMetadataID() == Metadata::DIArgListKind)
260 MDUsersWithID.push_back(&UseMap[Pair.first]);
261 }
262 llvm::sort(MDUsersWithID, [](auto UserA, auto UserB) {
263 return UserA->second < UserB->second;
264 });
266 for (auto *UserWithID : MDUsersWithID)
267 MDUsers.push_back(cast<Metadata *>(UserWithID->first));
268 return MDUsers;
269}
270
274 for (auto Pair : UseMap) {
275 OwnerTy Owner = Pair.second.first;
276 if (Owner.isNull())
277 continue;
278 if (!isa<DebugValueUser *>(Owner))
279 continue;
280 DVRUsersWithID.push_back(&UseMap[Pair.first]);
281 }
282 // Order DbgVariableRecord users in reverse-creation order. Normal dbg.value
283 // users of MetadataAsValues are ordered by their UseList, i.e. reverse order
284 // of when they were added: we need to replicate that here. The structure of
285 // debug-info output depends on the ordering of intrinsics, thus we need
286 // to keep them consistent for comparisons sake.
287 llvm::sort(DVRUsersWithID, [](auto UserA, auto UserB) {
288 return UserA->second > UserB->second;
289 });
291 for (auto UserWithID : DVRUsersWithID)
292 DVRUsers.push_back(cast<DebugValueUser *>(UserWithID->first)->getUser());
293 return DVRUsers;
294}
295
296void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
297 bool WasInserted =
298 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
299 .second;
300 (void)WasInserted;
301 assert(WasInserted && "Expected to add a reference");
302
303 ++NextIndex;
304 assert(NextIndex != 0 && "Unexpected overflow");
305}
306
307void ReplaceableMetadataImpl::dropRef(void *Ref) {
308 bool WasErased = UseMap.erase(Ref);
309 (void)WasErased;
310 assert(WasErased && "Expected to drop a reference");
311}
312
313void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
314 const Metadata &MD) {
315 auto I = UseMap.find(Ref);
316 assert(I != UseMap.end() && "Expected to move a reference");
317 auto OwnerAndIndex = I->second;
318 UseMap.erase(I);
319 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
320 (void)WasInserted;
321 assert(WasInserted && "Expected to add a reference");
322
323 // Check that the references are direct if there's no owner.
324 (void)MD;
325 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
326 "Reference without owner must be direct");
327 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
328 "Reference without owner must be direct");
329}
330
332 if (!C.isUsedByMetadata()) {
333 return;
334 }
335
336 LLVMContext &Context = C.getType()->getContext();
337 auto &Store = Context.pImpl->ValuesAsMetadata;
338 auto I = Store.find(&C);
339 ValueAsMetadata *MD = I->second;
340 using UseTy =
341 std::pair<void *, std::pair<MetadataTracking::OwnerTy, uint64_t>>;
342 // Copy out uses and update value of Constant used by debug info metadata with
343 // poison below
344 SmallVector<UseTy, 8> Uses(MD->UseMap.begin(), MD->UseMap.end());
345
346 for (const auto &Pair : Uses) {
347 MetadataTracking::OwnerTy Owner = Pair.second.first;
348 if (!Owner)
349 continue;
350 // Check for MetadataAsValue.
351 if (isa<MetadataAsValue *>(Owner)) {
352 cast<MetadataAsValue *>(Owner)->handleChangedMetadata(
354 continue;
355 }
356 if (!isa<Metadata *>(Owner))
357 continue;
358 auto *OwnerMD = dyn_cast_if_present<MDNode>(cast<Metadata *>(Owner));
359 if (!OwnerMD)
360 continue;
361 if (isa<DINode>(OwnerMD)) {
362 OwnerMD->handleChangedOperand(
363 Pair.first, ValueAsMetadata::get(PoisonValue::get(C.getType())));
364 }
365 }
366}
367
369 if (UseMap.empty())
370 return;
371
372 // Copy out uses since UseMap will get touched below.
373 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
374 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
375 llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
376 return L.second.second < R.second.second;
377 });
378 for (const auto &Pair : Uses) {
379 // Check that this Ref hasn't disappeared after RAUW (when updating a
380 // previous Ref).
381 if (!UseMap.count(Pair.first))
382 continue;
383
384 OwnerTy Owner = Pair.second.first;
385 if (!Owner) {
386 // Update unowned tracking references directly.
387 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
388 Ref = MD;
389 if (MD)
391 UseMap.erase(Pair.first);
392 continue;
393 }
394
395 // Check for MetadataAsValue.
396 if (isa<MetadataAsValue *>(Owner)) {
397 cast<MetadataAsValue *>(Owner)->handleChangedMetadata(MD);
398 continue;
399 }
400
401 if (auto *DVU = dyn_cast<DebugValueUser *>(Owner)) {
402 DVU->handleChangedValue(Pair.first, MD);
403 continue;
404 }
405
406 // There's a Metadata owner -- dispatch.
407 Metadata *OwnerMD = cast<Metadata *>(Owner);
408 switch (OwnerMD->getMetadataID()) {
409#define HANDLE_METADATA_LEAF(CLASS) \
410 case Metadata::CLASS##Kind: \
411 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
412 continue;
413#include "llvm/IR/Metadata.def"
414 default:
415 llvm_unreachable("Invalid metadata subclass");
416 }
417 }
418 assert(UseMap.empty() && "Expected all uses to be replaced");
419}
420
422 if (UseMap.empty())
423 return;
424
425 if (!ResolveUsers) {
426 UseMap.clear();
427 return;
428 }
429
430 // Copy out uses since UseMap could get touched below.
431 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
432 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
433 llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
434 return L.second.second < R.second.second;
435 });
436 UseMap.clear();
437 for (const auto &Pair : Uses) {
438 auto Owner = Pair.second.first;
439 if (!Owner)
440 continue;
441 if (!isa<Metadata *>(Owner))
442 continue;
443
444 // Resolve MDNodes that point at this.
445 auto *OwnerMD = dyn_cast_if_present<MDNode>(cast<Metadata *>(Owner));
446 if (!OwnerMD)
447 continue;
448 if (OwnerMD->isResolved())
449 continue;
450 OwnerMD->decrementUnresolvedOperandCount();
451 }
452}
453
454// Special handing of DIArgList is required in the RemoveDIs project, see
455// commentry in DIArgList::handleChangedOperand for details. Hidden behind
456// conditional compilation to avoid a compile time regression.
457ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
458 if (auto *N = dyn_cast<MDNode>(&MD)) {
459 return !N->isResolved() || N->isAlwaysReplaceable()
460 ? N->Context.getOrCreateReplaceableUses()
461 : nullptr;
462 }
463 if (auto ArgList = dyn_cast<DIArgList>(&MD))
464 return ArgList;
465 return dyn_cast<ValueAsMetadata>(&MD);
466}
467
468ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
469 if (auto *N = dyn_cast<MDNode>(&MD)) {
470 return !N->isResolved() || N->isAlwaysReplaceable()
471 ? N->Context.getReplaceableUses()
472 : nullptr;
473 }
474 if (auto ArgList = dyn_cast<DIArgList>(&MD))
475 return ArgList;
476 return dyn_cast<ValueAsMetadata>(&MD);
477}
478
479bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
480 if (auto *N = dyn_cast<MDNode>(&MD))
481 return !N->isResolved() || N->isAlwaysReplaceable();
482 return isa<ValueAsMetadata>(&MD) || isa<DIArgList>(&MD);
483}
484
486 assert(V && "Expected value");
487 if (auto *A = dyn_cast<Argument>(V)) {
488 if (auto *Fn = A->getParent())
489 return Fn->getSubprogram();
490 return nullptr;
491 }
492
493 if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {
494 if (auto *Fn = BB->getParent())
495 return Fn->getSubprogram();
496 return nullptr;
497 }
498
499 return nullptr;
500}
501
503 assert(V && "Unexpected null Value");
504
505 auto &Context = V->getContext();
506 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
507 if (!Entry) {
508 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
509 "Expected constant or function-local value");
510 assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
511 V->IsUsedByMD = true;
512 if (auto *C = dyn_cast<Constant>(V))
513 Entry = new ConstantAsMetadata(C);
514 else
515 Entry = new LocalAsMetadata(V);
516 }
517
518 return Entry;
519}
520
522 assert(V && "Unexpected null Value");
523 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
524}
525
527 assert(V && "Expected valid value");
528
529 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
530 auto I = Store.find(V);
531 if (I == Store.end())
532 return;
533
534 // Remove old entry from the map.
535 ValueAsMetadata *MD = I->second;
536 assert(MD && "Expected valid metadata");
537 assert(MD->getValue() == V && "Expected valid mapping");
538 Store.erase(I);
539
540 // Delete the metadata.
541 MD->replaceAllUsesWith(nullptr);
542 delete MD;
543}
544
546 assert(From && "Expected valid value");
547 assert(To && "Expected valid value");
548 assert(From != To && "Expected changed value");
549 assert(&From->getContext() == &To->getContext() && "Expected same context");
550
551 LLVMContext &Context = From->getType()->getContext();
552 auto &Store = Context.pImpl->ValuesAsMetadata;
553 auto I = Store.find(From);
554 if (I == Store.end()) {
555 assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
556 return;
557 }
558
559 // Remove old entry from the map.
560 assert(From->IsUsedByMD && "Expected From to be used by metadata");
561 From->IsUsedByMD = false;
562 ValueAsMetadata *MD = I->second;
563 assert(MD && "Expected valid metadata");
564 assert(MD->getValue() == From && "Expected valid mapping");
565 Store.erase(I);
566
567 if (isa<LocalAsMetadata>(MD)) {
568 if (auto *C = dyn_cast<Constant>(To)) {
569 // Local became a constant.
571 delete MD;
572 return;
573 }
576 // DISubprogram changed.
577 MD->replaceAllUsesWith(nullptr);
578 delete MD;
579 return;
580 }
581 } else if (!isa<Constant>(To)) {
582 // Changed to function-local value.
583 MD->replaceAllUsesWith(nullptr);
584 delete MD;
585 return;
586 }
587
588 auto *&Entry = Store[To];
589 if (Entry) {
590 // The target already exists.
591 MD->replaceAllUsesWith(Entry);
592 delete MD;
593 return;
594 }
595
596 // Update MD in place (and update the map entry).
597 assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
598 To->IsUsedByMD = true;
599 MD->V = To;
600 Entry = MD;
601}
602
603//===----------------------------------------------------------------------===//
604// MDString implementation.
605//
606
608 auto &Store = Context.pImpl->MDStringCache;
609 auto I = Store.try_emplace(Str);
610 auto &MapEntry = I.first->getValue();
611 if (!I.second)
612 return &MapEntry;
613 MapEntry.Entry = &*I.first;
614 return &MapEntry;
615}
616
618 assert(Entry && "Expected to find string map entry");
619 return Entry->first();
621
622//===----------------------------------------------------------------------===//
623// MDNode implementation.
624//
626// Assert that the MDNode types will not be unaligned by the objects
627// prepended to them.
628#define HANDLE_MDNODE_LEAF(CLASS) \
629 static_assert( \
630 alignof(uint64_t) >= alignof(CLASS), \
631 "Alignment is insufficient after objects prepended to " #CLASS);
632#include "llvm/IR/Metadata.def"
633
634void *MDNode::operator new(size_t Size, size_t NumOps, StorageType Storage) {
635 // uint64_t is the most aligned type we need support (ensured by static_assert
636 // above)
637 size_t AllocSize =
638 alignTo(Header::getAllocSize(Storage, NumOps), alignof(uint64_t));
639 char *Mem = reinterpret_cast<char *>(::operator new(AllocSize + Size));
640 Header *H = new (Mem + AllocSize - sizeof(Header)) Header(NumOps, Storage);
641 return reinterpret_cast<void *>(H + 1);
642}
643
644void MDNode::operator delete(void *N) {
645 Header *H = reinterpret_cast<Header *>(N) - 1;
646 void *Mem = H->getAllocation();
647 H->~Header();
648 ::operator delete(Mem);
649}
650
651MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
653 : Metadata(ID, Storage), Context(Context) {
654 unsigned Op = 0;
655 for (Metadata *MD : Ops1)
656 setOperand(Op++, MD);
657 for (Metadata *MD : Ops2)
658 setOperand(Op++, MD);
659
660 if (!isUniqued())
661 return;
662
663 // Count the unresolved operands. If there are any, RAUW support will be
664 // added lazily on first reference.
665 countUnresolvedOperands();
666}
667
668TempMDNode MDNode::clone() const {
669 switch (getMetadataID()) {
670 default:
671 llvm_unreachable("Invalid MDNode subclass");
672#define HANDLE_MDNODE_LEAF(CLASS) \
673 case CLASS##Kind: \
674 return cast<CLASS>(this)->cloneImpl();
675#include "llvm/IR/Metadata.def"
676 }
677}
678
679MDNode::Header::Header(size_t NumOps, StorageType Storage) {
680 IsLarge = isLarge(NumOps);
681 IsResizable = isResizable(Storage);
682 SmallSize = getSmallSize(NumOps, IsResizable, IsLarge);
683 if (IsLarge) {
684 SmallNumOps = 0;
685 new (getLargePtr()) LargeStorageVector();
686 getLarge().resize(NumOps);
687 return;
688 }
689 SmallNumOps = NumOps;
690 MDOperand *O = reinterpret_cast<MDOperand *>(this) - SmallSize;
691 for (MDOperand *E = O + SmallSize; O != E;)
692 (void)new (O++) MDOperand();
693}
694
695MDNode::Header::~Header() {
696 if (IsLarge) {
697 getLarge().~LargeStorageVector();
698 return;
699 }
700 MDOperand *O = reinterpret_cast<MDOperand *>(this);
701 for (MDOperand *E = O - SmallSize; O != E; --O)
702 (O - 1)->~MDOperand();
703}
704
705void *MDNode::Header::getSmallPtr() {
706 static_assert(alignof(MDOperand) <= alignof(Header),
707 "MDOperand too strongly aligned");
708 return reinterpret_cast<char *>(const_cast<Header *>(this)) -
709 sizeof(MDOperand) * SmallSize;
710}
711
712void MDNode::Header::resize(size_t NumOps) {
713 assert(IsResizable && "Node is not resizable");
714 if (operands().size() == NumOps)
715 return;
716
717 if (IsLarge)
718 getLarge().resize(NumOps);
719 else if (NumOps <= SmallSize)
720 resizeSmall(NumOps);
721 else
722 resizeSmallToLarge(NumOps);
723}
724
725void MDNode::Header::resizeSmall(size_t NumOps) {
726 assert(!IsLarge && "Expected a small MDNode");
727 assert(NumOps <= SmallSize && "NumOps too large for small resize");
728
729 MutableArrayRef<MDOperand> ExistingOps = operands();
730 assert(NumOps != ExistingOps.size() && "Expected a different size");
731
732 int NumNew = (int)NumOps - (int)ExistingOps.size();
733 MDOperand *O = ExistingOps.end();
734 for (int I = 0, E = NumNew; I < E; ++I)
735 (O++)->reset();
736 for (int I = 0, E = NumNew; I > E; --I)
737 (--O)->reset();
738 SmallNumOps = NumOps;
739 assert(O == operands().end() && "Operands not (un)initialized until the end");
740}
741
742void MDNode::Header::resizeSmallToLarge(size_t NumOps) {
743 assert(!IsLarge && "Expected a small MDNode");
744 assert(NumOps > SmallSize && "Expected NumOps to be larger than allocation");
745 LargeStorageVector NewOps;
746 NewOps.resize(NumOps);
747 llvm::move(operands(), NewOps.begin());
748 resizeSmall(0);
749 new (getLargePtr()) LargeStorageVector(std::move(NewOps));
750 IsLarge = true;
751}
752
754 if (auto *N = dyn_cast_or_null<MDNode>(Op))
755 return !N->isResolved();
756 return false;
757}
758
759void MDNode::countUnresolvedOperands() {
760 assert(getNumUnresolved() == 0 && "Expected unresolved ops to be uncounted");
761 assert(isUniqued() && "Expected this to be uniqued");
763}
764
765void MDNode::makeUniqued() {
766 assert(isTemporary() && "Expected this to be temporary");
767 assert(!isResolved() && "Expected this to be unresolved");
768
769 // Enable uniquing callbacks.
770 for (auto &Op : mutable_operands())
771 Op.reset(Op.get(), this);
772
773 // Make this 'uniqued'.
775 countUnresolvedOperands();
776 if (!getNumUnresolved()) {
777 dropReplaceableUses();
778 assert(isResolved() && "Expected this to be resolved");
779 }
780
781 assert(isUniqued() && "Expected this to be uniqued");
782}
783
784void MDNode::makeDistinct() {
785 assert(isTemporary() && "Expected this to be temporary");
786 assert(!isResolved() && "Expected this to be unresolved");
787
788 // Drop RAUW support and store as a distinct node.
789 dropReplaceableUses();
791
792 assert(isDistinct() && "Expected this to be distinct");
793 assert(isResolved() && "Expected this to be resolved");
794}
795
797 assert(isUniqued() && "Expected this to be uniqued");
798 assert(!isResolved() && "Expected this to be unresolved");
799
801 dropReplaceableUses();
802
803 assert(isResolved() && "Expected this to be resolved");
804}
805
806void MDNode::dropReplaceableUses() {
807 assert(!getNumUnresolved() && "Unexpected unresolved operand");
808
809 // Drop any RAUW support.
810 if (Context.hasReplaceableUses())
811 Context.takeReplaceableUses()->resolveAllUses();
812}
813
814void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
815 assert(isUniqued() && "Expected this to be uniqued");
816 assert(getNumUnresolved() != 0 && "Expected unresolved operands");
817
818 // Check if an operand was resolved.
819 if (!isOperandUnresolved(Old)) {
820 if (isOperandUnresolved(New))
821 // An operand was un-resolved!
823 } else if (!isOperandUnresolved(New))
824 decrementUnresolvedOperandCount();
825}
826
827void MDNode::decrementUnresolvedOperandCount() {
828 assert(!isResolved() && "Expected this to be unresolved");
829 if (isTemporary())
830 return;
831
832 assert(isUniqued() && "Expected this to be uniqued");
834 if (getNumUnresolved())
835 return;
836
837 // Last unresolved operand has just been resolved.
838 dropReplaceableUses();
839 assert(isResolved() && "Expected this to become resolved");
840}
841
843 if (isResolved())
844 return;
845
846 // Resolve this node immediately.
847 resolve();
848
849 // Resolve all operands.
850 for (const auto &Op : operands()) {
851 auto *N = dyn_cast_or_null<MDNode>(Op);
852 if (!N)
853 continue;
854
855 assert(!N->isTemporary() &&
856 "Expected all forward declarations to be resolved");
857 if (!N->isResolved())
858 N->resolveCycles();
859 }
860}
861
862static bool hasSelfReference(MDNode *N) {
863 return llvm::is_contained(N->operands(), N);
864}
865
866MDNode *MDNode::replaceWithPermanentImpl() {
867 switch (getMetadataID()) {
868 default:
869 // If this type isn't uniquable, replace with a distinct node.
870 return replaceWithDistinctImpl();
871
872#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
873 case CLASS##Kind: \
874 break;
875#include "llvm/IR/Metadata.def"
876 }
877
878 // Even if this type is uniquable, self-references have to be distinct.
879 if (hasSelfReference(this))
880 return replaceWithDistinctImpl();
881 return replaceWithUniquedImpl();
882}
883
884MDNode *MDNode::replaceWithUniquedImpl() {
885 // Try to uniquify in place.
886 MDNode *UniquedNode = uniquify();
887
888 if (UniquedNode == this) {
889 makeUniqued();
890 return this;
891 }
892
893 // Collision, so RAUW instead.
894 replaceAllUsesWith(UniquedNode);
895 deleteAsSubclass();
896 return UniquedNode;
897}
898
899MDNode *MDNode::replaceWithDistinctImpl() {
900 makeDistinct();
901 return this;
902}
903
904void MDTuple::recalculateHash() {
905 setHash(MDTupleInfo::KeyTy::calculateHash(this));
906}
907
909 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
910 setOperand(I, nullptr);
911 if (Context.hasReplaceableUses()) {
912 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
913 (void)Context.takeReplaceableUses();
914 }
915}
916
917void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
918 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
919 assert(Op < getNumOperands() && "Expected valid operand");
920
921 if (!isUniqued()) {
922 // This node is not uniqued. Just set the operand and be done with it.
923 setOperand(Op, New);
924 return;
925 }
926
927 // This node is uniqued.
928 eraseFromStore();
929
930 Metadata *Old = getOperand(Op);
931 setOperand(Op, New);
932
933 // Drop uniquing for self-reference cycles and deleted constants.
934 if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
935 if (!isResolved())
936 resolve();
938 return;
939 }
940
941 // Re-unique the node.
942 auto *Uniqued = uniquify();
943 if (Uniqued == this) {
944 if (!isResolved())
945 resolveAfterOperandChange(Old, New);
946 return;
947 }
948
949 // Collision.
950 if (!isResolved()) {
951 // Still unresolved, so RAUW.
952 //
953 // First, clear out all operands to prevent any recursion (similar to
954 // dropAllReferences(), but we still need the use-list).
955 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
956 setOperand(O, nullptr);
957 if (Context.hasReplaceableUses())
958 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
959 deleteAsSubclass();
960 return;
961 }
962
963 // Store in non-uniqued form if RAUW isn't possible.
965}
966
967void MDNode::deleteAsSubclass() {
968 switch (getMetadataID()) {
969 default:
970 llvm_unreachable("Invalid subclass of MDNode");
971#define HANDLE_MDNODE_LEAF(CLASS) \
972 case CLASS##Kind: \
973 delete cast<CLASS>(this); \
974 break;
975#include "llvm/IR/Metadata.def"
976 }
977}
978
979template <class T, class InfoT>
981 if (T *U = getUniqued(Store, N))
982 return U;
983
984 Store.insert(N);
985 return N;
986}
987
988template <class NodeTy> struct MDNode::HasCachedHash {
989 using Yes = char[1];
990 using No = char[2];
991 template <class U, U Val> struct SFINAE {};
992
993 template <class U>
994 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
995 template <class U> static No &check(...);
996
997 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
998};
999
1000MDNode *MDNode::uniquify() {
1001 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
1002
1003 // Try to insert into uniquing store.
1004 switch (getMetadataID()) {
1005 default:
1006 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
1007#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
1008 case CLASS##Kind: { \
1009 CLASS *SubclassThis = cast<CLASS>(this); \
1010 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
1011 ShouldRecalculateHash; \
1012 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
1013 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
1014 }
1015#include "llvm/IR/Metadata.def"
1016 }
1017}
1018
1019void MDNode::eraseFromStore() {
1020 switch (getMetadataID()) {
1021 default:
1022 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
1023#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
1024 case CLASS##Kind: \
1025 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
1026 break;
1027#include "llvm/IR/Metadata.def"
1028 }
1029}
1030
1031MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1032 StorageType Storage, bool ShouldCreate) {
1033 unsigned Hash = 0;
1034 if (Storage == Uniqued) {
1035 MDTupleInfo::KeyTy Key(MDs);
1036 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
1037 return N;
1038 if (!ShouldCreate)
1039 return nullptr;
1040 Hash = Key.getHash();
1041 } else {
1042 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
1043 }
1044
1045 return storeImpl(new (MDs.size(), Storage)
1046 MDTuple(Context, Storage, Hash, MDs),
1047 Storage, Context.pImpl->MDTuples);
1048}
1049
1051 assert(N->isTemporary() && "Expected temporary node");
1052 N->replaceAllUsesWith(nullptr);
1053 N->deleteAsSubclass();
1054}
1055
1057 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
1058 assert(!getNumUnresolved() && "Unexpected unresolved nodes");
1059 Storage = Distinct;
1060 assert(isResolved() && "Expected this to be resolved");
1061
1062 // Reset the hash.
1063 switch (getMetadataID()) {
1064 default:
1065 llvm_unreachable("Invalid subclass of MDNode");
1066#define HANDLE_MDNODE_LEAF(CLASS) \
1067 case CLASS##Kind: { \
1068 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
1069 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
1070 break; \
1071 }
1072#include "llvm/IR/Metadata.def"
1073 }
1074
1075 getContext().pImpl->DistinctMDNodes.push_back(this);
1076}
1077
1079 if (getOperand(I) == New)
1080 return;
1081
1082 if (!isUniqued()) {
1083 setOperand(I, New);
1084 return;
1085 }
1086
1087 handleChangedOperand(mutable_begin() + I, New);
1088}
1089
1090void MDNode::setOperand(unsigned I, Metadata *New) {
1091 assert(I < getNumOperands());
1092 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
1093}
1094
1095/// Get a node or a self-reference that looks like it.
1096///
1097/// Special handling for finding self-references, for use by \a
1098/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
1099/// when self-referencing nodes were still uniqued. If the first operand has
1100/// the same operands as \c Ops, return the first operand instead.
1103 if (!Ops.empty())
1104 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
1105 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
1106 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
1107 if (Ops[I] != N->getOperand(I))
1108 return MDNode::get(Context, Ops);
1109 return N;
1110 }
1111
1112 return MDNode::get(Context, Ops);
1113}
1114
1116 if (!A)
1117 return B;
1118 if (!B)
1119 return A;
1120
1121 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
1122 MDs.insert(B->op_begin(), B->op_end());
1123
1124 // FIXME: This preserves long-standing behaviour, but is it really the right
1125 // behaviour? Or was that an unintended side-effect of node uniquing?
1126 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
1127}
1128
1130 if (!A || !B)
1131 return nullptr;
1132
1133 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
1134 SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
1135 MDs.remove_if([&](Metadata *MD) { return !BSet.count(MD); });
1136
1137 // FIXME: This preserves long-standing behaviour, but is it really the right
1138 // behaviour? Or was that an unintended side-effect of node uniquing?
1139 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
1140}
1141
1143 if (!A || !B)
1144 return nullptr;
1145
1146 // Take the intersection of domains then union the scopes
1147 // within those domains
1149 SmallPtrSet<const MDNode *, 16> IntersectDomains;
1151 for (const MDOperand &MDOp : A->operands())
1152 if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1153 if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
1154 ADomains.insert(Domain);
1155
1156 for (const MDOperand &MDOp : B->operands())
1157 if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1158 if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
1159 if (ADomains.contains(Domain)) {
1160 IntersectDomains.insert(Domain);
1161 MDs.insert(MDOp);
1162 }
1163
1164 for (const MDOperand &MDOp : A->operands())
1165 if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
1166 if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
1167 if (IntersectDomains.contains(Domain))
1168 MDs.insert(MDOp);
1169
1170 return MDs.empty() ? nullptr
1171 : getOrSelfReference(A->getContext(), MDs.getArrayRef());
1172}
1173
1175 if (!A || !B)
1176 return nullptr;
1177
1178 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
1179 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
1180 if (AVal < BVal)
1181 return A;
1182 return B;
1183}
1184
1185// Call instructions with branch weights are only used in SamplePGO as
1186// documented in
1187/// https://llvm.org/docs/BranchWeightMetadata.html#callinst).
1188MDNode *MDNode::mergeDirectCallProfMetadata(MDNode *A, MDNode *B,
1189 const Instruction *AInstr,
1190 const Instruction *BInstr) {
1191 assert(A && B && AInstr && BInstr && "Caller should guarantee");
1192 auto &Ctx = AInstr->getContext();
1193 MDBuilder MDHelper(Ctx);
1194
1195 // LLVM IR verifier verifies !prof metadata has at least 2 operands.
1196 assert(A->getNumOperands() >= 2 && B->getNumOperands() >= 2 &&
1197 "!prof annotations should have no less than 2 operands");
1198 MDString *AMDS = dyn_cast<MDString>(A->getOperand(0));
1199 MDString *BMDS = dyn_cast<MDString>(B->getOperand(0));
1200 // LLVM IR verfier verifies first operand is MDString.
1201 assert(AMDS != nullptr && BMDS != nullptr &&
1202 "first operand should be a non-null MDString");
1203 StringRef AProfName = AMDS->getString();
1204 StringRef BProfName = BMDS->getString();
1205 if (AProfName == MDProfLabels::BranchWeights &&
1206 BProfName == MDProfLabels::BranchWeights) {
1207 ConstantInt *AInstrWeight = mdconst::dyn_extract<ConstantInt>(
1208 A->getOperand(getBranchWeightOffset(A)));
1209 ConstantInt *BInstrWeight = mdconst::dyn_extract<ConstantInt>(
1210 B->getOperand(getBranchWeightOffset(B)));
1211 assert(AInstrWeight && BInstrWeight && "verified by LLVM verifier");
1212 return MDNode::get(Ctx,
1213 {MDHelper.createString(MDProfLabels::BranchWeights),
1214 MDHelper.createConstant(ConstantInt::get(
1215 Type::getInt64Ty(Ctx),
1216 SaturatingAdd(AInstrWeight->getZExtValue(),
1217 BInstrWeight->getZExtValue())))});
1218 }
1219 return nullptr;
1220}
1221
1222// Pass in both instructions and nodes. Instruction information (e.g.,
1223// instruction type) helps interpret profiles and make implementation clearer.
1225 const Instruction *AInstr,
1226 const Instruction *BInstr) {
1227 // Check that it is legal to merge prof metadata based on the opcode.
1228 auto IsLegal = [](const Instruction &I) -> bool {
1229 switch (I.getOpcode()) {
1230 case Instruction::Invoke:
1231 case Instruction::Br:
1232 case Instruction::Switch:
1233 case Instruction::Call:
1234 case Instruction::IndirectBr:
1235 case Instruction::Select:
1236 case Instruction::CallBr:
1237 return true;
1238 default:
1239 return false;
1240 }
1241 };
1242 if (AInstr && !IsLegal(*AInstr))
1243 return nullptr;
1244 if (BInstr && !IsLegal(*BInstr))
1245 return nullptr;
1246
1247 if (!(A && B)) {
1248 return A ? A : B;
1249 }
1250
1251 assert(AInstr->getMetadata(LLVMContext::MD_prof) == A &&
1252 "Caller should guarantee");
1253 assert(BInstr->getMetadata(LLVMContext::MD_prof) == B &&
1254 "Caller should guarantee");
1255
1256 const CallInst *ACall = dyn_cast<CallInst>(AInstr);
1257 const CallInst *BCall = dyn_cast<CallInst>(BInstr);
1258
1259 // Both ACall and BCall are direct callsites.
1260 if (ACall && BCall && ACall->getCalledFunction() &&
1261 BCall->getCalledFunction())
1262 return mergeDirectCallProfMetadata(A, B, AInstr, BInstr);
1263
1264 // The rest of the cases are not implemented but could be added
1265 // when there are use cases.
1266 return nullptr;
1267}
1268
1269static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
1270 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
1271}
1272
1273static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
1274 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
1275}
1276
1279 ConstantRange NewRange(Low->getValue(), High->getValue());
1280 unsigned Size = EndPoints.size();
1281 const APInt &LB = EndPoints[Size - 2]->getValue();
1282 const APInt &LE = EndPoints[Size - 1]->getValue();
1283 ConstantRange LastRange(LB, LE);
1284 if (canBeMerged(NewRange, LastRange)) {
1285 ConstantRange Union = LastRange.unionWith(NewRange);
1286 Type *Ty = High->getType();
1287 EndPoints[Size - 2] =
1288 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
1289 EndPoints[Size - 1] =
1290 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
1291 return true;
1292 }
1293 return false;
1294}
1295
1298 if (!EndPoints.empty())
1299 if (tryMergeRange(EndPoints, Low, High))
1300 return;
1301
1302 EndPoints.push_back(Low);
1303 EndPoints.push_back(High);
1304}
1305
1307 // Drop the callee_type metadata if either of the call instructions do not
1308 // have it.
1309 if (!A || !B)
1310 return nullptr;
1312 SmallPtrSet<Metadata *, 8> MergedCallees;
1313 auto AddUniqueCallees = [&AB, &MergedCallees](const MDNode *N) {
1314 for (Metadata *MD : N->operands()) {
1315 if (MergedCallees.insert(MD).second)
1316 AB.push_back(MD);
1317 }
1318 };
1319 AddUniqueCallees(A);
1320 AddUniqueCallees(B);
1321 return MDNode::get(A->getContext(), AB);
1322}
1323
1325 // Given two ranges, we want to compute the union of the ranges. This
1326 // is slightly complicated by having to combine the intervals and merge
1327 // the ones that overlap.
1328
1329 if (!A || !B)
1330 return nullptr;
1331
1332 if (A == B)
1333 return A;
1334
1335 // First, walk both lists in order of the lower boundary of each interval.
1336 // At each step, try to merge the new interval to the last one we added.
1338 unsigned AI = 0;
1339 unsigned BI = 0;
1340 unsigned AN = A->getNumOperands() / 2;
1341 unsigned BN = B->getNumOperands() / 2;
1342 while (AI < AN && BI < BN) {
1343 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
1344 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
1345
1346 if (ALow->getValue().slt(BLow->getValue())) {
1347 addRange(EndPoints, ALow,
1348 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1349 ++AI;
1350 } else {
1351 addRange(EndPoints, BLow,
1352 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1353 ++BI;
1354 }
1355 }
1356 while (AI < AN) {
1357 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1358 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
1359 ++AI;
1360 }
1361 while (BI < BN) {
1362 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1363 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
1364 ++BI;
1365 }
1366
1367 // We haven't handled wrap in the previous merge,
1368 // if we have at least 2 ranges (4 endpoints) we have to try to merge
1369 // the last and first ones.
1370 unsigned Size = EndPoints.size();
1371 if (Size > 2) {
1372 ConstantInt *FB = EndPoints[0];
1373 ConstantInt *FE = EndPoints[1];
1374 if (tryMergeRange(EndPoints, FB, FE)) {
1375 for (unsigned i = 0; i < Size - 2; ++i) {
1376 EndPoints[i] = EndPoints[i + 2];
1377 }
1378 EndPoints.resize(Size - 2);
1379 }
1380 }
1381
1382 // If in the end we have a single range, it is possible that it is now the
1383 // full range. Just drop the metadata in that case.
1384 if (EndPoints.size() == 2) {
1385 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
1386 if (Range.isFullSet())
1387 return nullptr;
1388 }
1389
1391 MDs.reserve(EndPoints.size());
1392 for (auto *I : EndPoints)
1394 return MDNode::get(A->getContext(), MDs);
1395}
1396
1398 if (!A || !B)
1399 return nullptr;
1400
1401 if (A == B)
1402 return A;
1403
1404 SmallVector<ConstantRange> RangeListA, RangeListB;
1405 for (unsigned I = 0, E = A->getNumOperands() / 2; I != E; ++I) {
1406 auto *LowA = mdconst::extract<ConstantInt>(A->getOperand(2 * I + 0));
1407 auto *HighA = mdconst::extract<ConstantInt>(A->getOperand(2 * I + 1));
1408 RangeListA.push_back(ConstantRange(LowA->getValue(), HighA->getValue()));
1409 }
1410
1411 for (unsigned I = 0, E = B->getNumOperands() / 2; I != E; ++I) {
1412 auto *LowB = mdconst::extract<ConstantInt>(B->getOperand(2 * I + 0));
1413 auto *HighB = mdconst::extract<ConstantInt>(B->getOperand(2 * I + 1));
1414 RangeListB.push_back(ConstantRange(LowB->getValue(), HighB->getValue()));
1415 }
1416
1417 ConstantRangeList CRLA(RangeListA);
1418 ConstantRangeList CRLB(RangeListB);
1419 ConstantRangeList Result = CRLA.intersectWith(CRLB);
1420 if (Result.empty())
1421 return nullptr;
1422
1424 for (const ConstantRange &CR : Result) {
1426 ConstantInt::get(A->getContext(), CR.getLower())));
1428 ConstantInt::get(A->getContext(), CR.getUpper())));
1429 }
1430
1431 return MDNode::get(A->getContext(), MDs);
1432}
1433
1435 if (!A || !B)
1436 return nullptr;
1437
1438 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1439 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1440 if (AVal->getZExtValue() < BVal->getZExtValue())
1441 return A;
1442 return B;
1443}
1444
1445//===----------------------------------------------------------------------===//
1446// NamedMDNode implementation.
1447//
1448
1451}
1452
1453NamedMDNode::NamedMDNode(const Twine &N)
1454 : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
1455
1458 delete &getNMDOps(Operands);
1459}
1460
1462 return (unsigned)getNMDOps(Operands).size();
1463}
1464
1466 assert(i < getNumOperands() && "Invalid Operand number!");
1467 auto *N = getNMDOps(Operands)[i].get();
1468 return cast_or_null<MDNode>(N);
1469}
1470
1471void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
1472
1473void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1474 assert(I < getNumOperands() && "Invalid operand number");
1475 getNMDOps(Operands)[I].reset(New);
1476}
1477
1479
1480void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
1481
1483
1484//===----------------------------------------------------------------------===//
1485// Instruction Metadata method implementations.
1486//
1487
1489 for (const auto &A : Attachments)
1490 if (A.MDKind == ID)
1491 return A.Node;
1492 return nullptr;
1493}
1494
1495void MDAttachments::get(unsigned ID, SmallVectorImpl<MDNode *> &Result) const {
1496 for (const auto &A : Attachments)
1497 if (A.MDKind == ID)
1498 Result.push_back(A.Node);
1499}
1500
1502 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1503 for (const auto &A : Attachments)
1504 Result.emplace_back(A.MDKind, A.Node);
1505
1506 // Sort the resulting array so it is stable with respect to metadata IDs. We
1507 // need to preserve the original insertion order though.
1508 if (Result.size() > 1)
1509 llvm::stable_sort(Result, less_first());
1510}
1511
1512void MDAttachments::set(unsigned ID, MDNode *MD) {
1513 erase(ID);
1514 if (MD)
1515 insert(ID, *MD);
1516}
1517
1518void MDAttachments::insert(unsigned ID, MDNode &MD) {
1519 Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1520}
1521
1522bool MDAttachments::erase(unsigned ID) {
1523 if (empty())
1524 return false;
1525
1526 // Common case is one value.
1527 if (Attachments.size() == 1 && Attachments.back().MDKind == ID) {
1528 Attachments.pop_back();
1529 return true;
1530 }
1531
1532 auto OldSize = Attachments.size();
1533 llvm::erase_if(Attachments,
1534 [ID](const Attachment &A) { return A.MDKind == ID; });
1535 return OldSize != Attachments.size();
1536}
1537
1539 if (!hasMetadata())
1540 return nullptr;
1541 unsigned KindID = getContext().getMDKindID(Kind);
1542 return getMetadataImpl(KindID);
1543}
1544
1545MDNode *Value::getMetadataImpl(unsigned KindID) const {
1546 const LLVMContext &Ctx = getContext();
1547 const MDAttachments &Attachements = Ctx.pImpl->ValueMetadata.at(this);
1548 return Attachements.lookup(KindID);
1549}
1550
1551void Value::getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const {
1552 if (hasMetadata())
1553 getContext().pImpl->ValueMetadata.at(this).get(KindID, MDs);
1554}
1555
1557 if (hasMetadata())
1558 getMetadata(getContext().getMDKindID(Kind), MDs);
1559}
1560
1562 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1563 if (hasMetadata()) {
1564 assert(getContext().pImpl->ValueMetadata.count(this) &&
1565 "bit out of sync with hash table");
1566 const MDAttachments &Info = getContext().pImpl->ValueMetadata.at(this);
1567 Info.getAll(MDs);
1568 }
1569}
1570
1571void Value::setMetadata(unsigned KindID, MDNode *Node) {
1572 assert(isa<Instruction>(this) || isa<GlobalObject>(this));
1573
1574 // Handle the case when we're adding/updating metadata on a value.
1575 if (Node) {
1577 assert(!Info.empty() == HasMetadata && "bit out of sync with hash table");
1578 if (Info.empty())
1579 HasMetadata = true;
1580 Info.set(KindID, Node);
1581 return;
1582 }
1583
1584 // Otherwise, we're removing metadata from an instruction.
1585 assert((HasMetadata == (getContext().pImpl->ValueMetadata.count(this) > 0)) &&
1586 "bit out of sync with hash table");
1587 if (!HasMetadata)
1588 return; // Nothing to remove!
1589 MDAttachments &Info = getContext().pImpl->ValueMetadata.find(this)->second;
1590
1591 // Handle removal of an existing value.
1592 Info.erase(KindID);
1593 if (!Info.empty())
1594 return;
1595 getContext().pImpl->ValueMetadata.erase(this);
1596 HasMetadata = false;
1597}
1598
1600 if (!Node && !HasMetadata)
1601 return;
1602 setMetadata(getContext().getMDKindID(Kind), Node);
1603}
1604
1605void Value::addMetadata(unsigned KindID, MDNode &MD) {
1606 assert(isa<Instruction>(this) || isa<GlobalObject>(this));
1607 if (!HasMetadata)
1608 HasMetadata = true;
1609 getContext().pImpl->ValueMetadata[this].insert(KindID, MD);
1610}
1611
1613 addMetadata(getContext().getMDKindID(Kind), MD);
1614}
1615
1616bool Value::eraseMetadata(unsigned KindID) {
1617 // Nothing to unset.
1618 if (!HasMetadata)
1619 return false;
1620
1621 MDAttachments &Store = getContext().pImpl->ValueMetadata.find(this)->second;
1622 bool Changed = Store.erase(KindID);
1623 if (Store.empty())
1624 clearMetadata();
1625 return Changed;
1626}
1627
1628void Value::eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred) {
1629 if (!HasMetadata)
1630 return;
1631
1632 auto &MetadataStore = getContext().pImpl->ValueMetadata;
1633 MDAttachments &Info = MetadataStore.find(this)->second;
1634 assert(!Info.empty() && "bit out of sync with hash table");
1635 Info.remove_if([Pred](const MDAttachments::Attachment &I) {
1636 return Pred(I.MDKind, I.Node);
1637 });
1638
1639 if (Info.empty())
1640 clearMetadata();
1641}
1642
1644 if (!HasMetadata)
1645 return;
1646 assert(getContext().pImpl->ValueMetadata.count(this) &&
1647 "bit out of sync with hash table");
1648 getContext().pImpl->ValueMetadata.erase(this);
1649 HasMetadata = false;
1650}
1651
1653 if (!Node && !hasMetadata())
1654 return;
1655 setMetadata(getContext().getMDKindID(Kind), Node);
1656}
1657
1658MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
1659 const LLVMContext &Ctx = getContext();
1660 unsigned KindID = Ctx.getMDKindID(Kind);
1661 if (KindID == LLVMContext::MD_dbg)
1662 return DbgLoc.getAsMDNode();
1663 return Value::getMetadata(KindID);
1664}
1665
1666void Instruction::eraseMetadataIf(function_ref<bool(unsigned, MDNode *)> Pred) {
1667 if (DbgLoc && Pred(LLVMContext::MD_dbg, DbgLoc.getAsMDNode()))
1668 DbgLoc = {};
1669
1671}
1672
1674 if (!Value::hasMetadata())
1675 return; // Nothing to remove!
1676
1677 SmallSet<unsigned, 32> KnownSet(llvm::from_range, KnownIDs);
1678
1679 // A DIAssignID attachment is debug metadata, don't drop it.
1680 KnownSet.insert(LLVMContext::MD_DIAssignID);
1681
1682 Value::eraseMetadataIf([&KnownSet](unsigned MDKind, MDNode *Node) {
1683 return !KnownSet.count(MDKind);
1684 });
1685}
1686
1687void Instruction::updateDIAssignIDMapping(DIAssignID *ID) {
1688 auto &IDToInstrs = getContext().pImpl->AssignmentIDToInstrs;
1689 if (const DIAssignID *CurrentID =
1690 cast_or_null<DIAssignID>(getMetadata(LLVMContext::MD_DIAssignID))) {
1691 // Nothing to do if the ID isn't changing.
1692 if (ID == CurrentID)
1693 return;
1694
1695 // Unmap this instruction from its current ID.
1696 auto InstrsIt = IDToInstrs.find(CurrentID);
1697 assert(InstrsIt != IDToInstrs.end() &&
1698 "Expect existing attachment to be mapped");
1699
1700 auto &InstVec = InstrsIt->second;
1701 auto *InstIt = llvm::find(InstVec, this);
1702 assert(InstIt != InstVec.end() &&
1703 "Expect instruction to be mapped to attachment");
1704 // The vector contains a ptr to this. If this is the only element in the
1705 // vector, remove the ID:vector entry, otherwise just remove the
1706 // instruction from the vector.
1707 if (InstVec.size() == 1)
1708 IDToInstrs.erase(InstrsIt);
1709 else
1710 InstVec.erase(InstIt);
1711 }
1712
1713 // Map this instruction to the new ID.
1714 if (ID)
1715 IDToInstrs[ID].push_back(this);
1716}
1717
1718void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1719 if (!Node && !hasMetadata())
1720 return;
1721
1722 // Handle 'dbg' as a special case since it is not stored in the hash table.
1723 if (KindID == LLVMContext::MD_dbg) {
1724 DbgLoc = DebugLoc(Node);
1725 return;
1726 }
1727
1728 // Update DIAssignID to Instruction(s) mapping.
1729 if (KindID == LLVMContext::MD_DIAssignID) {
1730 // The DIAssignID tracking infrastructure doesn't support RAUWing temporary
1731 // nodes with DIAssignIDs. The cast_or_null below would also catch this, but
1732 // having a dedicated assert helps make this obvious.
1733 assert((!Node || !Node->isTemporary()) &&
1734 "Temporary DIAssignIDs are invalid");
1735 updateDIAssignIDMapping(cast_or_null<DIAssignID>(Node));
1736 }
1737
1738 Value::setMetadata(KindID, Node);
1739}
1740
1743 if (auto *Existing = getMetadata(LLVMContext::MD_annotation)) {
1744 SmallSetVector<StringRef, 2> AnnotationsSet(Annotations.begin(),
1745 Annotations.end());
1746 auto *Tuple = cast<MDTuple>(Existing);
1747 for (auto &N : Tuple->operands()) {
1748 if (isa<MDString>(N.get())) {
1749 Names.push_back(N);
1750 continue;
1751 }
1752 auto *MDAnnotationTuple = cast<MDTuple>(N);
1753 if (any_of(MDAnnotationTuple->operands(), [&AnnotationsSet](auto &Op) {
1754 return AnnotationsSet.contains(cast<MDString>(Op)->getString());
1755 }))
1756 return;
1757 Names.push_back(N);
1758 }
1759 }
1760
1761 MDBuilder MDB(getContext());
1762 SmallVector<Metadata *> MDAnnotationStrings;
1763 for (StringRef Annotation : Annotations)
1764 MDAnnotationStrings.push_back(MDB.createString(Annotation));
1765 MDNode *InfoTuple = MDTuple::get(getContext(), MDAnnotationStrings);
1766 Names.push_back(InfoTuple);
1767 MDNode *MD = MDTuple::get(getContext(), Names);
1768 setMetadata(LLVMContext::MD_annotation, MD);
1769}
1770
1773 if (auto *Existing = getMetadata(LLVMContext::MD_annotation)) {
1774 auto *Tuple = cast<MDTuple>(Existing);
1775 for (auto &N : Tuple->operands()) {
1776 if (isa<MDString>(N.get()) &&
1777 cast<MDString>(N.get())->getString() == Name)
1778 return;
1779 Names.push_back(N.get());
1780 }
1781 }
1782
1783 MDBuilder MDB(getContext());
1784 Names.push_back(MDB.createString(Name));
1785 MDNode *MD = MDTuple::get(getContext(), Names);
1786 setMetadata(LLVMContext::MD_annotation, MD);
1787}
1788
1790 AAMDNodes Result;
1791 // Not using Instruction::hasMetadata() because we're not interested in
1792 // DebugInfoMetadata.
1793 if (Value::hasMetadata()) {
1794 const MDAttachments &Info = getContext().pImpl->ValueMetadata.at(this);
1795 Result.TBAA = Info.lookup(LLVMContext::MD_tbaa);
1796 Result.TBAAStruct = Info.lookup(LLVMContext::MD_tbaa_struct);
1797 Result.Scope = Info.lookup(LLVMContext::MD_alias_scope);
1798 Result.NoAlias = Info.lookup(LLVMContext::MD_noalias);
1799 Result.NoAliasAddrSpace = Info.lookup(LLVMContext::MD_noalias_addrspace);
1800 }
1801 return Result;
1802}
1803
1805 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
1806 setMetadata(LLVMContext::MD_tbaa_struct, N.TBAAStruct);
1807 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1808 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
1809 setMetadata(LLVMContext::MD_noalias_addrspace, N.NoAliasAddrSpace);
1810}
1811
1813 setMetadata(llvm::LLVMContext::MD_nosanitize,
1815}
1816
1817void Instruction::getAllMetadataImpl(
1818 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1819 Result.clear();
1820
1821 // Handle 'dbg' as a special case since it is not stored in the hash table.
1822 if (DbgLoc) {
1823 Result.push_back(
1824 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
1825 }
1826 Value::getAllMetadata(Result);
1827}
1828
1830 assert(
1831 (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select ||
1832 getOpcode() == Instruction::Call || getOpcode() == Instruction::Invoke ||
1833 getOpcode() == Instruction::IndirectBr ||
1834 getOpcode() == Instruction::Switch) &&
1835 "Looking for branch weights on something besides branch");
1836
1837 return ::extractProfTotalWeight(*this, TotalVal);
1838}
1839
1842 Other->getAllMetadata(MDs);
1843 for (auto &MD : MDs) {
1844 // We need to adjust the type metadata offset.
1845 if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1846 auto *OffsetConst = cast<ConstantInt>(
1847 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1848 Metadata *TypeId = MD.second->getOperand(1);
1849 auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1850 OffsetConst->getType(), OffsetConst->getValue() + Offset));
1851 addMetadata(LLVMContext::MD_type,
1852 *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1853 continue;
1854 }
1855 // If an offset adjustment was specified we need to modify the DIExpression
1856 // to prepend the adjustment:
1857 // !DIExpression(DW_OP_plus, Offset, [original expr])
1858 auto *Attachment = MD.second;
1859 if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
1860 DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
1861 DIExpression *E = nullptr;
1862 if (!GV) {
1863 auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1864 GV = GVE->getVariable();
1865 E = GVE->getExpression();
1866 }
1867 ArrayRef<uint64_t> OrigElements;
1868 if (E)
1869 OrigElements = E->getElements();
1870 std::vector<uint64_t> Elements(OrigElements.size() + 2);
1871 Elements[0] = dwarf::DW_OP_plus_uconst;
1872 Elements[1] = Offset;
1873 llvm::copy(OrigElements, Elements.begin() + 2);
1874 E = DIExpression::get(getContext(), Elements);
1875 Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
1876 }
1877 addMetadata(MD.first, *Attachment);
1878 }
1879}
1880
1883 LLVMContext::MD_type,
1885 {ConstantAsMetadata::get(ConstantInt::get(
1887 TypeID}));
1888}
1889
1891 // Remove any existing vcall visibility metadata first in case we are
1892 // updating.
1893 eraseMetadata(LLVMContext::MD_vcall_visibility);
1894 addMetadata(LLVMContext::MD_vcall_visibility,
1896 {ConstantAsMetadata::get(ConstantInt::get(
1898}
1899
1901 if (MDNode *MD = getMetadata(LLVMContext::MD_vcall_visibility)) {
1902 uint64_t Val = cast<ConstantInt>(
1903 cast<ConstantAsMetadata>(MD->getOperand(0))->getValue())
1904 ->getZExtValue();
1905 assert(Val <= 2 && "unknown vcall visibility!");
1906 return (VCallVisibility)Val;
1907 }
1909}
1910
1912 setMetadata(LLVMContext::MD_dbg, SP);
1913}
1914
1916 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1917}
1918
1920 if (DISubprogram *SP = getSubprogram()) {
1921 if (DICompileUnit *CU = SP->getUnit()) {
1922 return CU->getDebugInfoForProfiling();
1923 }
1924 }
1925 return false;
1926}
1927
1929 addMetadata(LLVMContext::MD_dbg, *GV);
1930}
1931
1935 getMetadata(LLVMContext::MD_dbg, MDs);
1936 for (MDNode *MD : MDs)
1937 GVs.push_back(cast<DIGlobalVariableExpression>(MD));
1938}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
static const Function * getParent(const Value *V)
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Domain getDomain(const ConstantRange &CR)
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live value
This file defines the DenseSet and SmallDenseSet classes.
std::string Name
uint64_t Size
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
Module.h This file contains the declarations for the Module class.
#define I(x, y, z)
Definition: MD5.cpp:58
#define H(x, y, z)
Definition: MD5.cpp:57
mir Rename Register Operands
static DISubprogram * getLocalFunctionMetadata(Value *V)
Definition: Metadata.cpp:485
static Metadata * canonicalizeMetadataForValue(LLVMContext &Context, Metadata *MD)
Canonicalize metadata arguments to intrinsics.
Definition: Metadata.cpp:81
static bool isOperandUnresolved(Metadata *Op)
Definition: Metadata.cpp:753
static bool hasSelfReference(MDNode *N)
Definition: Metadata.cpp:862
static void addRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
Definition: Metadata.cpp:1296
static SmallVector< TrackingMDRef, 4 > & getNMDOps(void *Operands)
Definition: Metadata.cpp:1449
static bool canBeMerged(const ConstantRange &A, const ConstantRange &B)
Definition: Metadata.cpp:1273
static T * uniquifyImpl(T *N, DenseSet< T *, InfoT > &Store)
Definition: Metadata.cpp:980
static bool isContiguous(const ConstantRange &A, const ConstantRange &B)
Definition: Metadata.cpp:1269
static MDNode * getOrSelfReference(LLVMContext &Context, ArrayRef< Metadata * > Ops)
Get a node or a self-reference that looks like it.
Definition: Metadata.cpp:1101
static bool tryMergeRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
Definition: Metadata.cpp:1277
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
This file contains the declarations for profiling metadata utility functions.
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
Class for arbitrary precision integers.
Definition: APInt.h:78
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1130
This is a simple wrapper around an MDNode which provides a higher-level interface by hiding the detai...
Definition: Metadata.h:1589
Annotations lets you mark points and ranges inside source code, for tests:
Definition: Annotations.h:53
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:147
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:142
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1348
This class represents a function call, abstracting a target machine's calling convention.
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:535
This is the shared class of boolean and integer constants.
Definition: Constants.h:87
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:163
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:154
This class represents a list of constant ranges.
LLVM_ABI ConstantRangeList intersectWith(const ConstantRangeList &CRL) const
Return the range list that results from the intersection of this ConstantRangeList with another Const...
This class represents a range of values.
Definition: ConstantRange.h:47
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
This is an important base class in LLVM.
Definition: Constant.h:43
Assignment ID.
DWARF expression.
ArrayRef< uint64_t > getElements() const
A pair of DIGlobalVariable and DIExpression.
Subprogram description. Uses SubclassData1.
This class represents an Operation in the Expression.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition: DebugLoc.h:124
MDNode * getAsMDNode() const
Return this as a bar MDNode.
Definition: DebugLoc.h:291
Base class for tracking ValueAsMetadata/DIArgLists with user lookups and Owner callbacks outside of V...
Definition: Metadata.h:219
LLVM_ABI void handleChangedValue(void *Old, Metadata *NewDebugValue)
To be called by ReplaceableMetadataImpl::replaceAllUsesWith, where Old is a pointer to one of the poi...
Definition: Metadata.cpp:158
std::array< Metadata *, 3 > DebugValues
Definition: Metadata.h:225
void resetDebugValue(size_t Idx, Metadata *DebugValue)
Definition: Metadata.h:280
LLVM_ABI DbgVariableRecord * getUser()
Definition: Metadata.cpp:151
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
Definition: Metadata.cpp:1911
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1915
bool shouldEmitDebugInfoForProfiling() const
Returns true if we should emit debug info for profiling.
Definition: Metadata.cpp:1919
LLVM_ABI void addTypeMetadata(unsigned Offset, Metadata *TypeID)
Definition: Metadata.cpp:1881
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1571
LLVM_ABI void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
Definition: Metadata.cpp:1840
LLVM_ABI VCallVisibility getVCallVisibility() const
Definition: Metadata.cpp:1900
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
Definition: Metadata.cpp:1616
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1605
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Value.h:576
LLVM_ABI void setVCallVisibilityMetadata(VCallVisibility Visibility)
Definition: Metadata.cpp:1890
unsigned Visibility
Definition: GlobalValue.h:101
LLVM_ABI void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression * > &GVs) const
Fill the vector with all debug info attachements.
Definition: Metadata.cpp:1932
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Definition: Metadata.cpp:1928
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1804
LLVM_ABI bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
Definition: Metadata.cpp:1829
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
Definition: Instruction.h:406
LLVM_ABI void addAnnotationMetadata(StringRef Annotation)
Adds an !annotation metadata node with Annotation to this instruction.
Definition: Metadata.cpp:1771
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:428
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1718
LLVM_ABI void setNoSanitizeMetadata()
Sets the nosanitize metadata on this instruction.
Definition: Metadata.cpp:1812
LLVM_ABI void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
Definition: Metadata.cpp:1673
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
Definition: Metadata.cpp:1789
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:312
LLVM_ABI void eraseMetadataIf(function_ref< bool(unsigned, MDNode *)> Pred)
Erase all metadata that matches the predicate.
Definition: Metadata.cpp:1666
DenseMap< Metadata *, MetadataAsValue * > MetadataAsValues
DenseMap< DIAssignID *, SmallVector< Instruction *, 1 > > AssignmentIDToInstrs
Map DIAssignID -> Instructions with that attachment.
std::vector< MDNode * > DistinctMDNodes
DenseMap< const Value *, MDAttachments > ValueMetadata
Collection of metadata used in this context.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
LLVM_ABI unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:70
Multimap-like storage for metadata attachments.
void insert(unsigned ID, MDNode &MD)
Adds an attachment to a particular node.
Definition: Metadata.cpp:1518
void get(unsigned ID, SmallVectorImpl< MDNode * > &Result) const
Appends all attachments with the given ID to Result in insertion order.
Definition: Metadata.cpp:1495
void getAll(SmallVectorImpl< std::pair< unsigned, MDNode * > > &Result) const
Appends all attachments for the global to Result, sorting by attachment ID.
Definition: Metadata.cpp:1501
void set(unsigned ID, MDNode *MD)
Set an attachment to a particular node.
Definition: Metadata.cpp:1512
MDNode * lookup(unsigned ID) const
Returns the first attachment with the given ID or nullptr if no such attachment exists.
Definition: Metadata.cpp:1488
bool erase(unsigned ID)
Remove attachments with the given ID.
Definition: Metadata.cpp:1522
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
Definition: MDBuilder.cpp:21
Metadata node.
Definition: Metadata.h:1077
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1142
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
Definition: Metadata.cpp:1078
LLVM_ABI void resolveCycles()
Resolve cycles.
Definition: Metadata.cpp:842
mutable_op_range mutable_operands()
Definition: Metadata.h:1215
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
Definition: Metadata.cpp:1306
void replaceAllUsesWith(Metadata *MD)
RAUW a temporary.
Definition: Metadata.h:1281
static LLVM_ABI MDNode * concatenate(MDNode *A, MDNode *B)
Methods for metadata merging.
Definition: Metadata.cpp:1115
static LLVM_ABI void deleteTemporary(MDNode *N)
Deallocate a node created by getTemporary.
Definition: Metadata.cpp:1050
LLVM_ABI void resolve()
Resolve a unique, unresolved node.
Definition: Metadata.cpp:796
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1445
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1397
LLVM_ABI void storeDistinctInContext()
Definition: Metadata.cpp:1056
bool isTemporary() const
Definition: Metadata.h:1261
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1443
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1565
static LLVM_ABI MDNode * getMergedProfMetadata(MDNode *A, MDNode *B, const Instruction *AInstr, const Instruction *BInstr)
Merge !prof metadata from two instructions.
Definition: Metadata.cpp:1224
bool isUniqued() const
Definition: Metadata.h:1259
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1174
void setNumUnresolved(unsigned N)
Definition: Metadata.h:1368
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1451
MDOperand * mutable_begin()
Definition: Metadata.h:1210
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
Definition: Metadata.cpp:651
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
Definition: Metadata.cpp:668
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1324
bool isDistinct() const
Definition: Metadata.h:1260
LLVM_ABI void setOperand(unsigned I, Metadata *New)
Set an operand.
Definition: Metadata.cpp:1090
bool isResolved() const
Check if node is fully resolved.
Definition: Metadata.h:1257
op_iterator op_begin() const
Definition: Metadata.h:1435
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1129
static T * storeImpl(T *N, StorageType Storage, StoreT &Store)
Definition: MetadataImpl.h:42
LLVMContext & getContext() const
Definition: Metadata.h:1241
LLVM_ABI void dropAllReferences()
Definition: Metadata.cpp:908
static LLVM_ABI MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
Definition: Metadata.cpp:1434
unsigned getNumUnresolved() const
Definition: Metadata.h:1366
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:899
void reset()
Definition: Metadata.h:933
A single uniqued string.
Definition: Metadata.h:720
LLVM_ABI StringRef getString() const
Definition: Metadata.cpp:617
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:607
Tuple of metadata.
Definition: Metadata.h:1493
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1522
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:182
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:103
static LLVM_ABI MetadataAsValue * getIfExists(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:111
LLVM_ABI ~MetadataAsValue()
Definition: Metadata.cpp:65
static LLVM_ABI bool isReplaceable(const Metadata &MD)
Check whether metadata is replaceable.
Definition: Metadata.cpp:246
static void untrack(Metadata *&MD)
Stop tracking a reference to metadata.
Definition: Metadata.h:356
static bool retrack(Metadata *&MD, Metadata *&New)
Move tracking from one reference to another.
Definition: Metadata.h:367
static bool track(Metadata *&MD)
Track the reference to metadata.
Definition: Metadata.h:322
Root of the metadata hierarchy.
Definition: Metadata.h:63
StorageType
Active type of storage.
Definition: Metadata.h:71
unsigned char Storage
Storage flag for non-uniqued, otherwise unowned, metadata.
Definition: Metadata.h:74
unsigned getMetadataID() const
Definition: Metadata.h:103
void eraseNamedMetadata(NamedMDNode *NMD)
Remove the given NamedMDNode from this module and delete it.
Definition: Module.cpp:316
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:303
iterator end() const
Definition: ArrayRef.h:348
LLVM_ABI void setOperand(unsigned I, MDNode *New)
Definition: Metadata.cpp:1473
LLVM_ABI ~NamedMDNode()
Definition: Metadata.cpp:1456
LLVM_ABI StringRef getName() const
Definition: Metadata.cpp:1482
void dropAllReferences()
Remove all uses and clear node vector.
Definition: Metadata.h:1818
LLVM_ABI void eraseFromParent()
Drop all references and remove the node from parent module.
Definition: Metadata.cpp:1478
LLVM_ABI MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1465
LLVM_ABI unsigned getNumOperands() const
Definition: Metadata.cpp:1461
LLVM_ABI void clearOperands()
Drop all references to this node's operands.
Definition: Metadata.cpp:1480
Module * getParent()
Get the module that holds this named metadata collection.
Definition: Metadata.h:1823
LLVM_ABI void addOperand(MDNode *M)
Definition: Metadata.cpp:1471
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
Definition: PointerUnion.h:118
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Definition: PointerUnion.h:142
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1885
Shared implementation of use-lists for replaceable metadata.
Definition: Metadata.h:389
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition: Metadata.cpp:331
LLVM_ABI void replaceAllUsesWith(Metadata *MD)
Replace all uses of this with MD.
Definition: Metadata.cpp:368
LLVM_ABI SmallVector< DbgVariableRecord * > getAllDbgVariableRecordUsers()
Returns the list of all DbgVariableRecord users of this.
Definition: Metadata.cpp:272
LLVM_ABI void resolveAllUses(bool ResolveUsers=true)
Resolve all uses of this.
Definition: Metadata.cpp:421
LLVM_ABI SmallVector< Metadata * > getAllArgListUsers()
Returns the list of all DIArgList users of this.
Definition: Metadata.cpp:250
ArrayRef< value_type > getArrayRef() const
Definition: SetVector.h:90
bool remove_if(UnaryPredicate P)
Remove items from the set vector based on a predicate function.
Definition: SetVector.h:247
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:99
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:168
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:470
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:401
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:476
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:356
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:182
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
void reserve(size_type N)
Definition: SmallVector.h:664
void resize(size_type N)
Definition: SmallVector.h:639
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
Tracking metadata reference.
Definition: TrackingMDRef.h:25
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:54
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
static LLVM_ABI Type * getMetadataTy(LLVMContext &C)
Value wrapper in the Metadata hierarchy.
Definition: Metadata.h:457
void replaceAllUsesWith(Metadata *MD)
Handle collisions after Value::replaceAllUsesWith().
Definition: Metadata.h:517
static LLVM_ABI void handleDeletion(Value *V)
Definition: Metadata.cpp:526
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:502
static LLVM_ABI ValueAsMetadata * getIfExists(Value *V)
Definition: Metadata.cpp:521
static LLVM_ABI void handleRAUW(Value *From, Value *To)
Definition: Metadata.cpp:545
Value * getValue() const
Definition: Metadata.h:497
LLVM Value Representation.
Definition: Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
unsigned IsUsedByMD
Definition: Value.h:112
bool hasMetadata() const
Return true if this value has any metadata attached to it.
Definition: Value.h:602
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1571
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:546
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
Definition: Metadata.cpp:1561
LLVM_ABI MDNode * getMetadataImpl(unsigned KindID) const
Get metadata for the given kind, if any.
Definition: Metadata.cpp:1545
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
Definition: Metadata.cpp:1616
unsigned HasMetadata
Definition: Value.h:114
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1605
LLVM_ABI void eraseMetadataIf(function_ref< bool(unsigned, MDNode *)> Pred)
Erase all metadata attachments matching the given predicate.
Definition: Metadata.cpp:1628
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1098
LLVM_ABI void clearMetadata()
Erase all metadata attached to this Value.
Definition: Metadata.cpp:1643
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Value.h:576
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Key
PAL metadata keys.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
LLVM_ABI const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
Definition: Path.cpp:235
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
@ Offset
Definition: DWP.cpp:477
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition: STLExtras.h:860
void stable_sort(R &&Range)
Definition: STLExtras.h:2077
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1770
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1702
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
static T * getUniqued(DenseSet< T *, InfoT > &Store, const typename InfoT::KeyTy &Key)
Definition: MetadataImpl.h:22
constexpr from_range_t from_range
TypedTrackingMDRef< MDNode > TrackingMDNodeRef
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1751
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1669
@ Ref
The access may reference the value stored in memory.
@ Other
Any other memory.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1854
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition: STLExtras.h:1980
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2139
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1916
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition: MathExtras.h:614
#define N
static Yes & check(SFINAE< void(U::*)(unsigned), &U::setHash > *)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:760
static LLVM_ABI const char * BranchWeights
Definition: ProfDataUtils.h:25
Function object to check whether the first component of a container supported by std::get (like std::...
Definition: STLExtras.h:1472