LLVM  mainline
Metadata.cpp
Go to the documentation of this file.
00001 //===- Metadata.cpp - Implement Metadata classes --------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Metadata classes.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Metadata.h"
00015 #include "LLVMContextImpl.h"
00016 #include "MetadataImpl.h"
00017 #include "SymbolTableListTraitsImpl.h"
00018 #include "llvm/ADT/DenseMap.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SmallSet.h"
00021 #include "llvm/ADT/SmallString.h"
00022 #include "llvm/ADT/StringMap.h"
00023 #include "llvm/IR/ConstantRange.h"
00024 #include "llvm/IR/DebugInfoMetadata.h"
00025 #include "llvm/IR/Instruction.h"
00026 #include "llvm/IR/LLVMContext.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/IR/ValueHandle.h"
00029 
00030 using namespace llvm;
00031 
00032 MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
00033     : Value(Ty, MetadataAsValueVal), MD(MD) {
00034   track();
00035 }
00036 
00037 MetadataAsValue::~MetadataAsValue() {
00038   getType()->getContext().pImpl->MetadataAsValues.erase(MD);
00039   untrack();
00040 }
00041 
00042 /// \brief Canonicalize metadata arguments to intrinsics.
00043 ///
00044 /// To support bitcode upgrades (and assembly semantic sugar) for \a
00045 /// MetadataAsValue, we need to canonicalize certain metadata.
00046 ///
00047 ///   - nullptr is replaced by an empty MDNode.
00048 ///   - An MDNode with a single null operand is replaced by an empty MDNode.
00049 ///   - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
00050 ///
00051 /// This maintains readability of bitcode from when metadata was a type of
00052 /// value, and these bridges were unnecessary.
00053 static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
00054                                               Metadata *MD) {
00055   if (!MD)
00056     // !{}
00057     return MDNode::get(Context, None);
00058 
00059   // Return early if this isn't a single-operand MDNode.
00060   auto *N = dyn_cast<MDNode>(MD);
00061   if (!N || N->getNumOperands() != 1)
00062     return MD;
00063 
00064   if (!N->getOperand(0))
00065     // !{}
00066     return MDNode::get(Context, None);
00067 
00068   if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
00069     // Look through the MDNode.
00070     return C;
00071 
00072   return MD;
00073 }
00074 
00075 MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
00076   MD = canonicalizeMetadataForValue(Context, MD);
00077   auto *&Entry = Context.pImpl->MetadataAsValues[MD];
00078   if (!Entry)
00079     Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
00080   return Entry;
00081 }
00082 
00083 MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
00084                                               Metadata *MD) {
00085   MD = canonicalizeMetadataForValue(Context, MD);
00086   auto &Store = Context.pImpl->MetadataAsValues;
00087   return Store.lookup(MD);
00088 }
00089 
00090 void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
00091   LLVMContext &Context = getContext();
00092   MD = canonicalizeMetadataForValue(Context, MD);
00093   auto &Store = Context.pImpl->MetadataAsValues;
00094 
00095   // Stop tracking the old metadata.
00096   Store.erase(this->MD);
00097   untrack();
00098   this->MD = nullptr;
00099 
00100   // Start tracking MD, or RAUW if necessary.
00101   auto *&Entry = Store[MD];
00102   if (Entry) {
00103     replaceAllUsesWith(Entry);
00104     delete this;
00105     return;
00106   }
00107 
00108   this->MD = MD;
00109   track();
00110   Entry = this;
00111 }
00112 
00113 void MetadataAsValue::track() {
00114   if (MD)
00115     MetadataTracking::track(&MD, *MD, *this);
00116 }
00117 
00118 void MetadataAsValue::untrack() {
00119   if (MD)
00120     MetadataTracking::untrack(MD);
00121 }
00122 
00123 void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
00124   bool WasInserted =
00125       UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
00126           .second;
00127   (void)WasInserted;
00128   assert(WasInserted && "Expected to add a reference");
00129 
00130   ++NextIndex;
00131   assert(NextIndex != 0 && "Unexpected overflow");
00132 }
00133 
00134 void ReplaceableMetadataImpl::dropRef(void *Ref) {
00135   bool WasErased = UseMap.erase(Ref);
00136   (void)WasErased;
00137   assert(WasErased && "Expected to drop a reference");
00138 }
00139 
00140 void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
00141                                       const Metadata &MD) {
00142   auto I = UseMap.find(Ref);
00143   assert(I != UseMap.end() && "Expected to move a reference");
00144   auto OwnerAndIndex = I->second;
00145   UseMap.erase(I);
00146   bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
00147   (void)WasInserted;
00148   assert(WasInserted && "Expected to add a reference");
00149 
00150   // Check that the references are direct if there's no owner.
00151   (void)MD;
00152   assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
00153          "Reference without owner must be direct");
00154   assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
00155          "Reference without owner must be direct");
00156 }
00157 
00158 void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
00159   assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
00160          "Expected non-temp node");
00161 
00162   if (UseMap.empty())
00163     return;
00164 
00165   // Copy out uses since UseMap will get touched below.
00166   typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
00167   SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
00168   std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
00169     return L.second.second < R.second.second;
00170   });
00171   for (const auto &Pair : Uses) {
00172     // Check that this Ref hasn't disappeared after RAUW (when updating a
00173     // previous Ref).
00174     if (!UseMap.count(Pair.first))
00175       continue;
00176 
00177     OwnerTy Owner = Pair.second.first;
00178     if (!Owner) {
00179       // Update unowned tracking references directly.
00180       Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
00181       Ref = MD;
00182       if (MD)
00183         MetadataTracking::track(Ref);
00184       UseMap.erase(Pair.first);
00185       continue;
00186     }
00187 
00188     // Check for MetadataAsValue.
00189     if (Owner.is<MetadataAsValue *>()) {
00190       Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
00191       continue;
00192     }
00193 
00194     // There's a Metadata owner -- dispatch.
00195     Metadata *OwnerMD = Owner.get<Metadata *>();
00196     switch (OwnerMD->getMetadataID()) {
00197 #define HANDLE_METADATA_LEAF(CLASS)                                            \
00198   case Metadata::CLASS##Kind:                                                  \
00199     cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD);                \
00200     continue;
00201 #include "llvm/IR/Metadata.def"
00202     default:
00203       llvm_unreachable("Invalid metadata subclass");
00204     }
00205   }
00206   assert(UseMap.empty() && "Expected all uses to be replaced");
00207 }
00208 
00209 void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
00210   if (UseMap.empty())
00211     return;
00212 
00213   if (!ResolveUsers) {
00214     UseMap.clear();
00215     return;
00216   }
00217 
00218   // Copy out uses since UseMap could get touched below.
00219   typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
00220   SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
00221   std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
00222     return L.second.second < R.second.second;
00223   });
00224   UseMap.clear();
00225   for (const auto &Pair : Uses) {
00226     auto Owner = Pair.second.first;
00227     if (!Owner)
00228       continue;
00229     if (Owner.is<MetadataAsValue *>())
00230       continue;
00231 
00232     // Resolve MDNodes that point at this.
00233     auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
00234     if (!OwnerMD)
00235       continue;
00236     if (OwnerMD->isResolved())
00237       continue;
00238     OwnerMD->decrementUnresolvedOperandCount();
00239   }
00240 }
00241 
00242 static Function *getLocalFunction(Value *V) {
00243   assert(V && "Expected value");
00244   if (auto *A = dyn_cast<Argument>(V))
00245     return A->getParent();
00246   if (BasicBlock *BB = cast<Instruction>(V)->getParent())
00247     return BB->getParent();
00248   return nullptr;
00249 }
00250 
00251 ValueAsMetadata *ValueAsMetadata::get(Value *V) {
00252   assert(V && "Unexpected null Value");
00253 
00254   auto &Context = V->getContext();
00255   auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
00256   if (!Entry) {
00257     assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
00258            "Expected constant or function-local value");
00259     assert(!V->NameAndIsUsedByMD.getInt() &&
00260            "Expected this to be the only metadata use");
00261     V->NameAndIsUsedByMD.setInt(true);
00262     if (auto *C = dyn_cast<Constant>(V))
00263       Entry = new ConstantAsMetadata(C);
00264     else
00265       Entry = new LocalAsMetadata(V);
00266   }
00267 
00268   return Entry;
00269 }
00270 
00271 ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
00272   assert(V && "Unexpected null Value");
00273   return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
00274 }
00275 
00276 void ValueAsMetadata::handleDeletion(Value *V) {
00277   assert(V && "Expected valid value");
00278 
00279   auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
00280   auto I = Store.find(V);
00281   if (I == Store.end())
00282     return;
00283 
00284   // Remove old entry from the map.
00285   ValueAsMetadata *MD = I->second;
00286   assert(MD && "Expected valid metadata");
00287   assert(MD->getValue() == V && "Expected valid mapping");
00288   Store.erase(I);
00289 
00290   // Delete the metadata.
00291   MD->replaceAllUsesWith(nullptr);
00292   delete MD;
00293 }
00294 
00295 void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
00296   assert(From && "Expected valid value");
00297   assert(To && "Expected valid value");
00298   assert(From != To && "Expected changed value");
00299   assert(From->getType() == To->getType() && "Unexpected type change");
00300 
00301   LLVMContext &Context = From->getType()->getContext();
00302   auto &Store = Context.pImpl->ValuesAsMetadata;
00303   auto I = Store.find(From);
00304   if (I == Store.end()) {
00305     assert(!From->NameAndIsUsedByMD.getInt() &&
00306            "Expected From not to be used by metadata");
00307     return;
00308   }
00309 
00310   // Remove old entry from the map.
00311   assert(From->NameAndIsUsedByMD.getInt() &&
00312          "Expected From to be used by metadata");
00313   From->NameAndIsUsedByMD.setInt(false);
00314   ValueAsMetadata *MD = I->second;
00315   assert(MD && "Expected valid metadata");
00316   assert(MD->getValue() == From && "Expected valid mapping");
00317   Store.erase(I);
00318 
00319   if (isa<LocalAsMetadata>(MD)) {
00320     if (auto *C = dyn_cast<Constant>(To)) {
00321       // Local became a constant.
00322       MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
00323       delete MD;
00324       return;
00325     }
00326     if (getLocalFunction(From) && getLocalFunction(To) &&
00327         getLocalFunction(From) != getLocalFunction(To)) {
00328       // Function changed.
00329       MD->replaceAllUsesWith(nullptr);
00330       delete MD;
00331       return;
00332     }
00333   } else if (!isa<Constant>(To)) {
00334     // Changed to function-local value.
00335     MD->replaceAllUsesWith(nullptr);
00336     delete MD;
00337     return;
00338   }
00339 
00340   auto *&Entry = Store[To];
00341   if (Entry) {
00342     // The target already exists.
00343     MD->replaceAllUsesWith(Entry);
00344     delete MD;
00345     return;
00346   }
00347 
00348   // Update MD in place (and update the map entry).
00349   assert(!To->NameAndIsUsedByMD.getInt() &&
00350          "Expected this to be the only metadata use");
00351   To->NameAndIsUsedByMD.setInt(true);
00352   MD->V = To;
00353   Entry = MD;
00354 }
00355 
00356 //===----------------------------------------------------------------------===//
00357 // MDString implementation.
00358 //
00359 
00360 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
00361   auto &Store = Context.pImpl->MDStringCache;
00362   auto I = Store.find(Str);
00363   if (I != Store.end())
00364     return &I->second;
00365 
00366   auto *Entry =
00367       StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
00368   bool WasInserted = Store.insert(Entry);
00369   (void)WasInserted;
00370   assert(WasInserted && "Expected entry to be inserted");
00371   Entry->second.Entry = Entry;
00372   return &Entry->second;
00373 }
00374 
00375 StringRef MDString::getString() const {
00376   assert(Entry && "Expected to find string map entry");
00377   return Entry->first();
00378 }
00379 
00380 //===----------------------------------------------------------------------===//
00381 // MDNode implementation.
00382 //
00383 
00384 void *MDNode::operator new(size_t Size, unsigned NumOps) {
00385   void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
00386   MDOperand *O = static_cast<MDOperand *>(Ptr);
00387   for (MDOperand *E = O + NumOps; O != E; ++O)
00388     (void)new (O) MDOperand;
00389   return O;
00390 }
00391 
00392 void MDNode::operator delete(void *Mem) {
00393   MDNode *N = static_cast<MDNode *>(Mem);
00394   MDOperand *O = static_cast<MDOperand *>(Mem);
00395   for (MDOperand *E = O - N->NumOperands; O != E; --O)
00396     (O - 1)->~MDOperand();
00397   ::operator delete(O);
00398 }
00399 
00400 MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
00401                ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
00402     : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
00403       NumUnresolved(0), Context(Context) {
00404   unsigned Op = 0;
00405   for (Metadata *MD : Ops1)
00406     setOperand(Op++, MD);
00407   for (Metadata *MD : Ops2)
00408     setOperand(Op++, MD);
00409 
00410   if (isDistinct())
00411     return;
00412 
00413   if (isUniqued())
00414     // Check whether any operands are unresolved, requiring re-uniquing.  If
00415     // not, don't support RAUW.
00416     if (!countUnresolvedOperands())
00417       return;
00418 
00419   this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
00420 }
00421 
00422 TempMDNode MDNode::clone() const {
00423   switch (getMetadataID()) {
00424   default:
00425     llvm_unreachable("Invalid MDNode subclass");
00426 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00427   case CLASS##Kind:                                                            \
00428     return cast<CLASS>(this)->cloneImpl();
00429 #include "llvm/IR/Metadata.def"
00430   }
00431 }
00432 
00433 static bool isOperandUnresolved(Metadata *Op) {
00434   if (auto *N = dyn_cast_or_null<MDNode>(Op))
00435     return !N->isResolved();
00436   return false;
00437 }
00438 
00439 unsigned MDNode::countUnresolvedOperands() {
00440   assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
00441   NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
00442   return NumUnresolved;
00443 }
00444 
00445 void MDNode::makeUniqued() {
00446   assert(isTemporary() && "Expected this to be temporary");
00447   assert(!isResolved() && "Expected this to be unresolved");
00448 
00449   // Make this 'uniqued'.
00450   Storage = Uniqued;
00451   if (!countUnresolvedOperands())
00452     resolve();
00453 
00454   assert(isUniqued() && "Expected this to be uniqued");
00455 }
00456 
00457 void MDNode::makeDistinct() {
00458   assert(isTemporary() && "Expected this to be temporary");
00459   assert(!isResolved() && "Expected this to be unresolved");
00460 
00461   // Pretend to be uniqued, resolve the node, and then store in distinct table.
00462   Storage = Uniqued;
00463   resolve();
00464   storeDistinctInContext();
00465 
00466   assert(isDistinct() && "Expected this to be distinct");
00467   assert(isResolved() && "Expected this to be resolved");
00468 }
00469 
00470 void MDNode::resolve() {
00471   assert(isUniqued() && "Expected this to be uniqued");
00472   assert(!isResolved() && "Expected this to be unresolved");
00473 
00474   // Move the map, so that this immediately looks resolved.
00475   auto Uses = Context.takeReplaceableUses();
00476   NumUnresolved = 0;
00477   assert(isResolved() && "Expected this to be resolved");
00478 
00479   // Drop RAUW support.
00480   Uses->resolveAllUses();
00481 }
00482 
00483 void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
00484   assert(NumUnresolved != 0 && "Expected unresolved operands");
00485 
00486   // Check if an operand was resolved.
00487   if (!isOperandUnresolved(Old)) {
00488     if (isOperandUnresolved(New))
00489       // An operand was un-resolved!
00490       ++NumUnresolved;
00491   } else if (!isOperandUnresolved(New))
00492     decrementUnresolvedOperandCount();
00493 }
00494 
00495 void MDNode::decrementUnresolvedOperandCount() {
00496   if (!--NumUnresolved)
00497     // Last unresolved operand has just been resolved.
00498     resolve();
00499 }
00500 
00501 void MDNode::resolveCycles() {
00502   if (isResolved())
00503     return;
00504 
00505   // Resolve this node immediately.
00506   resolve();
00507 
00508   // Resolve all operands.
00509   for (const auto &Op : operands()) {
00510     auto *N = dyn_cast_or_null<MDNode>(Op);
00511     if (!N)
00512       continue;
00513 
00514     assert(!N->isTemporary() &&
00515            "Expected all forward declarations to be resolved");
00516     if (!N->isResolved())
00517       N->resolveCycles();
00518   }
00519 }
00520 
00521 static bool hasSelfReference(MDNode *N) {
00522   for (Metadata *MD : N->operands())
00523     if (MD == N)
00524       return true;
00525   return false;
00526 }
00527 
00528 MDNode *MDNode::replaceWithPermanentImpl() {
00529   if (hasSelfReference(this))
00530     return replaceWithDistinctImpl();
00531   return replaceWithUniquedImpl();
00532 }
00533 
00534 MDNode *MDNode::replaceWithUniquedImpl() {
00535   // Try to uniquify in place.
00536   MDNode *UniquedNode = uniquify();
00537 
00538   if (UniquedNode == this) {
00539     makeUniqued();
00540     return this;
00541   }
00542 
00543   // Collision, so RAUW instead.
00544   replaceAllUsesWith(UniquedNode);
00545   deleteAsSubclass();
00546   return UniquedNode;
00547 }
00548 
00549 MDNode *MDNode::replaceWithDistinctImpl() {
00550   makeDistinct();
00551   return this;
00552 }
00553 
00554 void MDTuple::recalculateHash() {
00555   setHash(MDTupleInfo::KeyTy::calculateHash(this));
00556 }
00557 
00558 void MDNode::dropAllReferences() {
00559   for (unsigned I = 0, E = NumOperands; I != E; ++I)
00560     setOperand(I, nullptr);
00561   if (!isResolved()) {
00562     Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
00563     (void)Context.takeReplaceableUses();
00564   }
00565 }
00566 
00567 void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
00568   unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
00569   assert(Op < getNumOperands() && "Expected valid operand");
00570 
00571   if (!isUniqued()) {
00572     // This node is not uniqued.  Just set the operand and be done with it.
00573     setOperand(Op, New);
00574     return;
00575   }
00576 
00577   // This node is uniqued.
00578   eraseFromStore();
00579 
00580   Metadata *Old = getOperand(Op);
00581   setOperand(Op, New);
00582 
00583   // Drop uniquing for self-reference cycles.
00584   if (New == this) {
00585     if (!isResolved())
00586       resolve();
00587     storeDistinctInContext();
00588     return;
00589   }
00590 
00591   // Re-unique the node.
00592   auto *Uniqued = uniquify();
00593   if (Uniqued == this) {
00594     if (!isResolved())
00595       resolveAfterOperandChange(Old, New);
00596     return;
00597   }
00598 
00599   // Collision.
00600   if (!isResolved()) {
00601     // Still unresolved, so RAUW.
00602     //
00603     // First, clear out all operands to prevent any recursion (similar to
00604     // dropAllReferences(), but we still need the use-list).
00605     for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
00606       setOperand(O, nullptr);
00607     Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
00608     deleteAsSubclass();
00609     return;
00610   }
00611 
00612   // Store in non-uniqued form if RAUW isn't possible.
00613   storeDistinctInContext();
00614 }
00615 
00616 void MDNode::deleteAsSubclass() {
00617   switch (getMetadataID()) {
00618   default:
00619     llvm_unreachable("Invalid subclass of MDNode");
00620 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00621   case CLASS##Kind:                                                            \
00622     delete cast<CLASS>(this);                                                  \
00623     break;
00624 #include "llvm/IR/Metadata.def"
00625   }
00626 }
00627 
00628 template <class T, class InfoT>
00629 static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
00630   if (T *U = getUniqued(Store, N))
00631     return U;
00632 
00633   Store.insert(N);
00634   return N;
00635 }
00636 
00637 template <class NodeTy> struct MDNode::HasCachedHash {
00638   typedef char Yes[1];
00639   typedef char No[2];
00640   template <class U, U Val> struct SFINAE {};
00641 
00642   template <class U>
00643   static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
00644   template <class U> static No &check(...);
00645 
00646   static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
00647 };
00648 
00649 MDNode *MDNode::uniquify() {
00650   assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
00651 
00652   // Try to insert into uniquing store.
00653   switch (getMetadataID()) {
00654   default:
00655     llvm_unreachable("Invalid subclass of MDNode");
00656 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00657   case CLASS##Kind: {                                                          \
00658     CLASS *SubclassThis = cast<CLASS>(this);                                   \
00659     std::integral_constant<bool, HasCachedHash<CLASS>::value>                  \
00660         ShouldRecalculateHash;                                                 \
00661     dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash);              \
00662     return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s);           \
00663   }
00664 #include "llvm/IR/Metadata.def"
00665   }
00666 }
00667 
00668 void MDNode::eraseFromStore() {
00669   switch (getMetadataID()) {
00670   default:
00671     llvm_unreachable("Invalid subclass of MDNode");
00672 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00673   case CLASS##Kind:                                                            \
00674     getContext().pImpl->CLASS##s.erase(cast<CLASS>(this));                     \
00675     break;
00676 #include "llvm/IR/Metadata.def"
00677   }
00678 }
00679 
00680 MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
00681                           StorageType Storage, bool ShouldCreate) {
00682   unsigned Hash = 0;
00683   if (Storage == Uniqued) {
00684     MDTupleInfo::KeyTy Key(MDs);
00685     if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
00686       return N;
00687     if (!ShouldCreate)
00688       return nullptr;
00689     Hash = Key.getHash();
00690   } else {
00691     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
00692   }
00693 
00694   return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
00695                    Storage, Context.pImpl->MDTuples);
00696 }
00697 
00698 void MDNode::deleteTemporary(MDNode *N) {
00699   assert(N->isTemporary() && "Expected temporary node");
00700   N->replaceAllUsesWith(nullptr);
00701   N->deleteAsSubclass();
00702 }
00703 
00704 void MDNode::storeDistinctInContext() {
00705   assert(isResolved() && "Expected resolved nodes");
00706   Storage = Distinct;
00707 
00708   // Reset the hash.
00709   switch (getMetadataID()) {
00710   default:
00711     llvm_unreachable("Invalid subclass of MDNode");
00712 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
00713   case CLASS##Kind: {                                                          \
00714     std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
00715     dispatchResetHash(cast<CLASS>(this), ShouldResetHash);                     \
00716     break;                                                                     \
00717   }
00718 #include "llvm/IR/Metadata.def"
00719   }
00720 
00721   getContext().pImpl->DistinctMDNodes.insert(this);
00722 }
00723 
00724 void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
00725   if (getOperand(I) == New)
00726     return;
00727 
00728   if (!isUniqued()) {
00729     setOperand(I, New);
00730     return;
00731   }
00732 
00733   handleChangedOperand(mutable_begin() + I, New);
00734 }
00735 
00736 void MDNode::setOperand(unsigned I, Metadata *New) {
00737   assert(I < NumOperands);
00738   mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
00739 }
00740 
00741 /// \brief Get a node, or a self-reference that looks like it.
00742 ///
00743 /// Special handling for finding self-references, for use by \a
00744 /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
00745 /// when self-referencing nodes were still uniqued.  If the first operand has
00746 /// the same operands as \c Ops, return the first operand instead.
00747 static MDNode *getOrSelfReference(LLVMContext &Context,
00748                                   ArrayRef<Metadata *> Ops) {
00749   if (!Ops.empty())
00750     if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
00751       if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
00752         for (unsigned I = 1, E = Ops.size(); I != E; ++I)
00753           if (Ops[I] != N->getOperand(I))
00754             return MDNode::get(Context, Ops);
00755         return N;
00756       }
00757 
00758   return MDNode::get(Context, Ops);
00759 }
00760 
00761 MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
00762   if (!A)
00763     return B;
00764   if (!B)
00765     return A;
00766 
00767   SmallVector<Metadata *, 4> MDs;
00768   MDs.reserve(A->getNumOperands() + B->getNumOperands());
00769   MDs.append(A->op_begin(), A->op_end());
00770   MDs.append(B->op_begin(), B->op_end());
00771 
00772   // FIXME: This preserves long-standing behaviour, but is it really the right
00773   // behaviour?  Or was that an unintended side-effect of node uniquing?
00774   return getOrSelfReference(A->getContext(), MDs);
00775 }
00776 
00777 MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
00778   if (!A || !B)
00779     return nullptr;
00780 
00781   SmallVector<Metadata *, 4> MDs;
00782   for (Metadata *MD : A->operands())
00783     if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
00784       MDs.push_back(MD);
00785 
00786   // FIXME: This preserves long-standing behaviour, but is it really the right
00787   // behaviour?  Or was that an unintended side-effect of node uniquing?
00788   return getOrSelfReference(A->getContext(), MDs);
00789 }
00790 
00791 MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
00792   if (!A || !B)
00793     return nullptr;
00794 
00795   SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
00796   for (Metadata *MD : A->operands())
00797     if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
00798       MDs.push_back(MD);
00799 
00800   // FIXME: This preserves long-standing behaviour, but is it really the right
00801   // behaviour?  Or was that an unintended side-effect of node uniquing?
00802   return getOrSelfReference(A->getContext(), MDs);
00803 }
00804 
00805 MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
00806   if (!A || !B)
00807     return nullptr;
00808 
00809   APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
00810   APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
00811   if (AVal.compare(BVal) == APFloat::cmpLessThan)
00812     return A;
00813   return B;
00814 }
00815 
00816 static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
00817   return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
00818 }
00819 
00820 static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
00821   return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
00822 }
00823 
00824 static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
00825                           ConstantInt *Low, ConstantInt *High) {
00826   ConstantRange NewRange(Low->getValue(), High->getValue());
00827   unsigned Size = EndPoints.size();
00828   APInt LB = EndPoints[Size - 2]->getValue();
00829   APInt LE = EndPoints[Size - 1]->getValue();
00830   ConstantRange LastRange(LB, LE);
00831   if (canBeMerged(NewRange, LastRange)) {
00832     ConstantRange Union = LastRange.unionWith(NewRange);
00833     Type *Ty = High->getType();
00834     EndPoints[Size - 2] =
00835         cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
00836     EndPoints[Size - 1] =
00837         cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
00838     return true;
00839   }
00840   return false;
00841 }
00842 
00843 static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
00844                      ConstantInt *Low, ConstantInt *High) {
00845   if (!EndPoints.empty())
00846     if (tryMergeRange(EndPoints, Low, High))
00847       return;
00848 
00849   EndPoints.push_back(Low);
00850   EndPoints.push_back(High);
00851 }
00852 
00853 MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
00854   // Given two ranges, we want to compute the union of the ranges. This
00855   // is slightly complitade by having to combine the intervals and merge
00856   // the ones that overlap.
00857 
00858   if (!A || !B)
00859     return nullptr;
00860 
00861   if (A == B)
00862     return A;
00863 
00864   // First, walk both lists in older of the lower boundary of each interval.
00865   // At each step, try to merge the new interval to the last one we adedd.
00866   SmallVector<ConstantInt *, 4> EndPoints;
00867   int AI = 0;
00868   int BI = 0;
00869   int AN = A->getNumOperands() / 2;
00870   int BN = B->getNumOperands() / 2;
00871   while (AI < AN && BI < BN) {
00872     ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
00873     ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
00874 
00875     if (ALow->getValue().slt(BLow->getValue())) {
00876       addRange(EndPoints, ALow,
00877                mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
00878       ++AI;
00879     } else {
00880       addRange(EndPoints, BLow,
00881                mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
00882       ++BI;
00883     }
00884   }
00885   while (AI < AN) {
00886     addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
00887              mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
00888     ++AI;
00889   }
00890   while (BI < BN) {
00891     addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
00892              mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
00893     ++BI;
00894   }
00895 
00896   // If we have more than 2 ranges (4 endpoints) we have to try to merge
00897   // the last and first ones.
00898   unsigned Size = EndPoints.size();
00899   if (Size > 4) {
00900     ConstantInt *FB = EndPoints[0];
00901     ConstantInt *FE = EndPoints[1];
00902     if (tryMergeRange(EndPoints, FB, FE)) {
00903       for (unsigned i = 0; i < Size - 2; ++i) {
00904         EndPoints[i] = EndPoints[i + 2];
00905       }
00906       EndPoints.resize(Size - 2);
00907     }
00908   }
00909 
00910   // If in the end we have a single range, it is possible that it is now the
00911   // full range. Just drop the metadata in that case.
00912   if (EndPoints.size() == 2) {
00913     ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
00914     if (Range.isFullSet())
00915       return nullptr;
00916   }
00917 
00918   SmallVector<Metadata *, 4> MDs;
00919   MDs.reserve(EndPoints.size());
00920   for (auto *I : EndPoints)
00921     MDs.push_back(ConstantAsMetadata::get(I));
00922   return MDNode::get(A->getContext(), MDs);
00923 }
00924 
00925 //===----------------------------------------------------------------------===//
00926 // NamedMDNode implementation.
00927 //
00928 
00929 static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
00930   return *(SmallVector<TrackingMDRef, 4> *)Operands;
00931 }
00932 
00933 NamedMDNode::NamedMDNode(const Twine &N)
00934     : Name(N.str()), Parent(nullptr),
00935       Operands(new SmallVector<TrackingMDRef, 4>()) {}
00936 
00937 NamedMDNode::~NamedMDNode() {
00938   dropAllReferences();
00939   delete &getNMDOps(Operands);
00940 }
00941 
00942 unsigned NamedMDNode::getNumOperands() const {
00943   return (unsigned)getNMDOps(Operands).size();
00944 }
00945 
00946 MDNode *NamedMDNode::getOperand(unsigned i) const {
00947   assert(i < getNumOperands() && "Invalid Operand number!");
00948   auto *N = getNMDOps(Operands)[i].get();
00949   return cast_or_null<MDNode>(N);
00950 }
00951 
00952 void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
00953 
00954 void NamedMDNode::setOperand(unsigned I, MDNode *New) {
00955   assert(I < getNumOperands() && "Invalid operand number");
00956   getNMDOps(Operands)[I].reset(New);
00957 }
00958 
00959 void NamedMDNode::eraseFromParent() {
00960   getParent()->eraseNamedMetadata(this);
00961 }
00962 
00963 void NamedMDNode::dropAllReferences() {
00964   getNMDOps(Operands).clear();
00965 }
00966 
00967 StringRef NamedMDNode::getName() const {
00968   return StringRef(Name);
00969 }
00970 
00971 //===----------------------------------------------------------------------===//
00972 // Instruction Metadata method implementations.
00973 //
00974 
00975 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
00976   if (!Node && !hasMetadata())
00977     return;
00978   setMetadata(getContext().getMDKindID(Kind), Node);
00979 }
00980 
00981 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
00982   return getMetadataImpl(getContext().getMDKindID(Kind));
00983 }
00984 
00985 void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
00986   SmallSet<unsigned, 5> KnownSet;
00987   KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
00988 
00989   // Drop debug if needed
00990   if (KnownSet.erase(LLVMContext::MD_dbg))
00991     DbgLoc = DebugLoc();
00992 
00993   if (!hasMetadataHashEntry())
00994     return; // Nothing to remove!
00995 
00996   DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
00997       getContext().pImpl->MetadataStore;
00998 
00999   if (KnownSet.empty()) {
01000     // Just drop our entry at the store.
01001     MetadataStore.erase(this);
01002     setHasMetadataHashEntry(false);
01003     return;
01004   }
01005 
01006   LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
01007   unsigned I;
01008   unsigned E;
01009   // Walk the array and drop any metadata we don't know.
01010   for (I = 0, E = Info.size(); I != E;) {
01011     if (KnownSet.count(Info[I].first)) {
01012       ++I;
01013       continue;
01014     }
01015 
01016     Info[I] = std::move(Info.back());
01017     Info.pop_back();
01018     --E;
01019   }
01020   assert(E == Info.size());
01021 
01022   if (E == 0) {
01023     // Drop our entry at the store.
01024     MetadataStore.erase(this);
01025     setHasMetadataHashEntry(false);
01026   }
01027 }
01028 
01029 /// setMetadata - Set the metadata of of the specified kind to the specified
01030 /// node.  This updates/replaces metadata if already present, or removes it if
01031 /// Node is null.
01032 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
01033   if (!Node && !hasMetadata())
01034     return;
01035 
01036   // Handle 'dbg' as a special case since it is not stored in the hash table.
01037   if (KindID == LLVMContext::MD_dbg) {
01038     DbgLoc = DebugLoc(Node);
01039     return;
01040   }
01041   
01042   // Handle the case when we're adding/updating metadata on an instruction.
01043   if (Node) {
01044     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
01045     assert(!Info.empty() == hasMetadataHashEntry() &&
01046            "HasMetadata bit is wonked");
01047     if (Info.empty()) {
01048       setHasMetadataHashEntry(true);
01049     } else {
01050       // Handle replacement of an existing value.
01051       for (auto &P : Info)
01052         if (P.first == KindID) {
01053           P.second.reset(Node);
01054           return;
01055         }
01056     }
01057 
01058     // No replacement, just add it to the list.
01059     Info.emplace_back(std::piecewise_construct, std::make_tuple(KindID),
01060                       std::make_tuple(Node));
01061     return;
01062   }
01063 
01064   // Otherwise, we're removing metadata from an instruction.
01065   assert((hasMetadataHashEntry() ==
01066           (getContext().pImpl->MetadataStore.count(this) > 0)) &&
01067          "HasMetadata bit out of date!");
01068   if (!hasMetadataHashEntry())
01069     return;  // Nothing to remove!
01070   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
01071 
01072   // Common case is removing the only entry.
01073   if (Info.size() == 1 && Info[0].first == KindID) {
01074     getContext().pImpl->MetadataStore.erase(this);
01075     setHasMetadataHashEntry(false);
01076     return;
01077   }
01078 
01079   // Handle removal of an existing value.
01080   for (unsigned i = 0, e = Info.size(); i != e; ++i)
01081     if (Info[i].first == KindID) {
01082       Info[i] = std::move(Info.back());
01083       Info.pop_back();
01084       assert(!Info.empty() && "Removing last entry should be handled above");
01085       return;
01086     }
01087   // Otherwise, removing an entry that doesn't exist on the instruction.
01088 }
01089 
01090 void Instruction::setAAMetadata(const AAMDNodes &N) {
01091   setMetadata(LLVMContext::MD_tbaa, N.TBAA);
01092   setMetadata(LLVMContext::MD_alias_scope, N.Scope);
01093   setMetadata(LLVMContext::MD_noalias, N.NoAlias);
01094 }
01095 
01096 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
01097   // Handle 'dbg' as a special case since it is not stored in the hash table.
01098   if (KindID == LLVMContext::MD_dbg)
01099     return DbgLoc.getAsMDNode();
01100 
01101   if (!hasMetadataHashEntry()) return nullptr;
01102   
01103   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
01104   assert(!Info.empty() && "bit out of sync with hash table");
01105 
01106   for (const auto &I : Info)
01107     if (I.first == KindID)
01108       return I.second;
01109   return nullptr;
01110 }
01111 
01112 void Instruction::getAllMetadataImpl(
01113     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
01114   Result.clear();
01115   
01116   // Handle 'dbg' as a special case since it is not stored in the hash table.
01117   if (DbgLoc) {
01118     Result.push_back(
01119         std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
01120     if (!hasMetadataHashEntry()) return;
01121   }
01122   
01123   assert(hasMetadataHashEntry() &&
01124          getContext().pImpl->MetadataStore.count(this) &&
01125          "Shouldn't have called this");
01126   const LLVMContextImpl::MDMapTy &Info =
01127     getContext().pImpl->MetadataStore.find(this)->second;
01128   assert(!Info.empty() && "Shouldn't have called this");
01129 
01130   Result.reserve(Result.size() + Info.size());
01131   for (auto &I : Info)
01132     Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
01133 
01134   // Sort the resulting array so it is stable.
01135   if (Result.size() > 1)
01136     array_pod_sort(Result.begin(), Result.end());
01137 }
01138 
01139 void Instruction::getAllMetadataOtherThanDebugLocImpl(
01140     SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
01141   Result.clear();
01142   assert(hasMetadataHashEntry() &&
01143          getContext().pImpl->MetadataStore.count(this) &&
01144          "Shouldn't have called this");
01145   const LLVMContextImpl::MDMapTy &Info =
01146     getContext().pImpl->MetadataStore.find(this)->second;
01147   assert(!Info.empty() && "Shouldn't have called this");
01148   Result.reserve(Result.size() + Info.size());
01149   for (auto &I : Info)
01150     Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
01151 
01152   // Sort the resulting array so it is stable.
01153   if (Result.size() > 1)
01154     array_pod_sort(Result.begin(), Result.end());
01155 }
01156 
01157 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
01158 /// this instruction.
01159 void Instruction::clearMetadataHashEntries() {
01160   assert(hasMetadataHashEntry() && "Caller should check");
01161   getContext().pImpl->MetadataStore.erase(this);
01162   setHasMetadataHashEntry(false);
01163 }