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