1 //===-- Metadata.cpp - Implement Metadata classes -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Metadata classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Metadata.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/Instruction.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "SymbolTableListTraitsImpl.h"
24 #include "llvm/Support/LeakDetector.h"
25 #include "llvm/Support/ValueHandle.h"
28 //===----------------------------------------------------------------------===//
29 // MDString implementation.
32 void MDString::anchor() { }
34 MDString::MDString(LLVMContext &C, StringRef S)
35 : Value(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
37 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
38 LLVMContextImpl *pImpl = Context.pImpl;
39 StringMapEntry<MDString *> &Entry =
40 pImpl->MDStringCache.GetOrCreateValue(Str);
41 MDString *&S = Entry.getValue();
42 if (!S) S = new MDString(Context, Entry.getKey());
46 //===----------------------------------------------------------------------===//
47 // MDNodeOperand implementation.
50 // Use CallbackVH to hold MDNode operands.
52 class MDNodeOperand : public CallbackVH {
55 MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
62 virtual void deleted();
63 virtual void allUsesReplacedWith(Value *NV);
65 } // end namespace llvm.
68 void MDNodeOperand::deleted() {
69 Parent->replaceOperand(this, 0);
72 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
73 Parent->replaceOperand(this, NV);
78 //===----------------------------------------------------------------------===//
79 // MDNode implementation.
82 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
83 /// the end of the MDNode.
84 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
85 // Use <= instead of < to permit a one-past-the-end address.
86 assert(Op <= N->getNumOperands() && "Invalid operand number");
87 return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
90 MDNode::MDNode(LLVMContext &C, ArrayRef<Value*> Vals, bool isFunctionLocal)
91 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
92 NumOperands = Vals.size();
95 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
97 // Initialize the operand list, which is co-allocated on the end of the node.
99 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
101 new (Op) MDNodeOperand(Vals[i], this);
105 /// ~MDNode - Destroy MDNode.
107 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
108 "Not being destroyed through destroy()?");
109 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
110 if (isNotUniqued()) {
111 pImpl->NonUniquedMDNodes.erase(this);
113 pImpl->MDNodeSet.RemoveNode(this);
116 // Destroy the operands.
117 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
119 Op->~MDNodeOperand();
122 static const Function *getFunctionForValue(Value *V) {
124 if (Instruction *I = dyn_cast<Instruction>(V)) {
125 BasicBlock *BB = I->getParent();
126 return BB ? BB->getParent() : 0;
128 if (Argument *A = dyn_cast<Argument>(V))
129 return A->getParent();
130 if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
131 return BB->getParent();
132 if (MDNode *MD = dyn_cast<MDNode>(V))
133 return MD->getFunction();
138 static const Function *assertLocalFunction(const MDNode *N) {
139 if (!N->isFunctionLocal()) return 0;
141 // FIXME: This does not handle cyclic function local metadata.
142 const Function *F = 0, *NewF = 0;
143 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
144 if (Value *V = N->getOperand(i)) {
145 if (MDNode *MD = dyn_cast<MDNode>(V))
146 NewF = assertLocalFunction(MD);
148 NewF = getFunctionForValue(V);
153 assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
159 // getFunction - If this metadata is function-local and recursively has a
160 // function-local operand, return the first such operand's parent function.
161 // Otherwise, return null. getFunction() should not be used for performance-
162 // critical code because it recursively visits all the MDNode's operands.
163 const Function *MDNode::getFunction() const {
165 return assertLocalFunction(this);
167 if (!isFunctionLocal()) return NULL;
168 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
169 if (const Function *F = getFunctionForValue(getOperand(i)))
174 // destroy - Delete this node. Only when there are no uses.
175 void MDNode::destroy() {
176 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
177 // Placement delete, the free the memory.
182 /// isFunctionLocalValue - Return true if this is a value that would require a
183 /// function-local MDNode.
184 static bool isFunctionLocalValue(Value *V) {
185 return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
186 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
189 MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Value*> Vals,
190 FunctionLocalness FL, bool Insert) {
191 LLVMContextImpl *pImpl = Context.pImpl;
193 // Add all the operand pointers. Note that we don't have to add the
194 // isFunctionLocal bit because that's implied by the operands.
195 // Note that if the operands are later nulled out, the node will be
196 // removed from the uniquing map.
198 for (unsigned i = 0; i != Vals.size(); ++i)
199 ID.AddPointer(Vals[i]);
204 if ((N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)))
207 bool isFunctionLocal = false;
210 for (unsigned i = 0; i != Vals.size(); ++i) {
213 if (isFunctionLocalValue(V)) {
214 isFunctionLocal = true;
220 isFunctionLocal = false;
223 isFunctionLocal = true;
227 // Coallocate space for the node and Operands together, then placement new.
228 void *Ptr = malloc(sizeof(MDNode)+Vals.size()*sizeof(MDNodeOperand));
229 N = new (Ptr) MDNode(Context, Vals, isFunctionLocal);
231 // InsertPoint will have been set by the FindNodeOrInsertPos call.
232 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
237 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Value*> Vals) {
238 return getMDNode(Context, Vals, FL_Unknown);
241 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context,
242 ArrayRef<Value*> Vals,
243 bool isFunctionLocal) {
244 return getMDNode(Context, Vals, isFunctionLocal ? FL_Yes : FL_No);
247 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals) {
248 return getMDNode(Context, Vals, FL_Unknown, false);
251 MDNode *MDNode::getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals) {
253 (MDNode *)malloc(sizeof(MDNode)+Vals.size()*sizeof(MDNodeOperand));
254 N = new (N) MDNode(Context, Vals, FL_No);
255 N->setValueSubclassData(N->getSubclassDataFromValue() |
257 LeakDetector::addGarbageObject(N);
261 void MDNode::deleteTemporary(MDNode *N) {
262 assert(N->use_empty() && "Temporary MDNode has uses!");
263 assert(!N->getContext().pImpl->MDNodeSet.RemoveNode(N) &&
264 "Deleting a non-temporary uniqued node!");
265 assert(!N->getContext().pImpl->NonUniquedMDNodes.erase(N) &&
266 "Deleting a non-temporary non-uniqued node!");
267 assert((N->getSubclassDataFromValue() & NotUniquedBit) &&
268 "Temporary MDNode does not have NotUniquedBit set!");
269 assert((N->getSubclassDataFromValue() & DestroyFlag) == 0 &&
270 "Temporary MDNode has DestroyFlag set!");
271 LeakDetector::removeGarbageObject(N);
275 /// getOperand - Return specified operand.
276 Value *MDNode::getOperand(unsigned i) const {
277 return *getOperandPtr(const_cast<MDNode*>(this), i);
280 void MDNode::Profile(FoldingSetNodeID &ID) const {
281 // Add all the operand pointers. Note that we don't have to add the
282 // isFunctionLocal bit because that's implied by the operands.
283 // Note that if the operands are later nulled out, the node will be
284 // removed from the uniquing map.
285 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
286 ID.AddPointer(getOperand(i));
289 void MDNode::setIsNotUniqued() {
290 setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
291 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
292 pImpl->NonUniquedMDNodes.insert(this);
295 // Replace value from this node's operand list.
296 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
299 // If is possible that someone did GV->RAUW(inst), replacing a global variable
300 // with an instruction or some other function-local object. If this is a
301 // non-function-local MDNode, it can't point to a function-local object.
302 // Handle this case by implicitly dropping the MDNode reference to null.
303 // Likewise if the MDNode is function-local but for a different function.
304 if (To && isFunctionLocalValue(To)) {
305 if (!isFunctionLocal())
308 const Function *F = getFunction();
309 const Function *FV = getFunctionForValue(To);
310 // Metadata can be function-local without having an associated function.
311 // So only consider functions to have changed if non-null.
312 if (F && FV && F != FV)
320 // Update the operand.
323 // If this node is already not being uniqued (because one of the operands
324 // already went to null), then there is nothing else to do here.
325 if (isNotUniqued()) return;
327 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
329 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
330 // this node to remove it, so we don't care what state the operands are in.
331 pImpl->MDNodeSet.RemoveNode(this);
333 // If we are dropping an argument to null, we choose to not unique the MDNode
334 // anymore. This commonly occurs during destruction, and uniquing these
335 // brings little reuse. Also, this means we don't need to include
336 // isFunctionLocal bits in FoldingSetNodeIDs for MDNodes.
342 // Now that the node is out of the folding set, get ready to reinsert it.
343 // First, check to see if another node with the same operands already exists
344 // in the set. If so, then this node is redundant.
348 if (MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)) {
349 replaceAllUsesWith(N);
354 // InsertPoint will have been set by the FindNodeOrInsertPos call.
355 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
357 // If this MDValue was previously function-local but no longer is, clear
358 // its function-local flag.
359 if (isFunctionLocal() && !isFunctionLocalValue(To)) {
360 bool isStillFunctionLocal = false;
361 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
362 Value *V = getOperand(i);
364 if (isFunctionLocalValue(V)) {
365 isStillFunctionLocal = true;
369 if (!isStillFunctionLocal)
370 setValueSubclassData(getSubclassDataFromValue() & ~FunctionLocalBit);
374 //===----------------------------------------------------------------------===//
375 // NamedMDNode implementation.
378 static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
379 return *(SmallVector<TrackingVH<MDNode>, 4>*)Operands;
382 NamedMDNode::NamedMDNode(const Twine &N)
383 : Name(N.str()), Parent(0),
384 Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {
387 NamedMDNode::~NamedMDNode() {
389 delete &getNMDOps(Operands);
392 /// getNumOperands - Return number of NamedMDNode operands.
393 unsigned NamedMDNode::getNumOperands() const {
394 return (unsigned)getNMDOps(Operands).size();
397 /// getOperand - Return specified operand.
398 MDNode *NamedMDNode::getOperand(unsigned i) const {
399 assert(i < getNumOperands() && "Invalid Operand number!");
400 return dyn_cast<MDNode>(&*getNMDOps(Operands)[i]);
403 /// addOperand - Add metadata Operand.
404 void NamedMDNode::addOperand(MDNode *M) {
405 assert(!M->isFunctionLocal() &&
406 "NamedMDNode operands must not be function-local!");
407 getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
410 /// eraseFromParent - Drop all references and remove the node from parent
412 void NamedMDNode::eraseFromParent() {
413 getParent()->eraseNamedMetadata(this);
416 /// dropAllReferences - Remove all uses and clear node vector.
417 void NamedMDNode::dropAllReferences() {
418 getNMDOps(Operands).clear();
421 /// getName - Return a constant reference to this named metadata's name.
422 StringRef NamedMDNode::getName() const {
423 return StringRef(Name);
426 //===----------------------------------------------------------------------===//
427 // Instruction Metadata method implementations.
430 void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
431 if (Node == 0 && !hasMetadata()) return;
432 setMetadata(getContext().getMDKindID(Kind), Node);
435 MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
436 return getMetadataImpl(getContext().getMDKindID(Kind));
439 /// setMetadata - Set the metadata of of the specified kind to the specified
440 /// node. This updates/replaces metadata if already present, or removes it if
442 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
443 if (Node == 0 && !hasMetadata()) return;
445 // Handle 'dbg' as a special case since it is not stored in the hash table.
446 if (KindID == LLVMContext::MD_dbg) {
447 DbgLoc = DebugLoc::getFromDILocation(Node);
451 // Handle the case when we're adding/updating metadata on an instruction.
453 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
454 assert(!Info.empty() == hasMetadataHashEntry() &&
455 "HasMetadata bit is wonked");
457 setHasMetadataHashEntry(true);
459 // Handle replacement of an existing value.
460 for (unsigned i = 0, e = Info.size(); i != e; ++i)
461 if (Info[i].first == KindID) {
462 Info[i].second = Node;
467 // No replacement, just add it to the list.
468 Info.push_back(std::make_pair(KindID, Node));
472 // Otherwise, we're removing metadata from an instruction.
473 assert((hasMetadataHashEntry() ==
474 getContext().pImpl->MetadataStore.count(this)) &&
475 "HasMetadata bit out of date!");
476 if (!hasMetadataHashEntry())
477 return; // Nothing to remove!
478 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
480 // Common case is removing the only entry.
481 if (Info.size() == 1 && Info[0].first == KindID) {
482 getContext().pImpl->MetadataStore.erase(this);
483 setHasMetadataHashEntry(false);
487 // Handle removal of an existing value.
488 for (unsigned i = 0, e = Info.size(); i != e; ++i)
489 if (Info[i].first == KindID) {
490 Info[i] = Info.back();
492 assert(!Info.empty() && "Removing last entry should be handled above");
495 // Otherwise, removing an entry that doesn't exist on the instruction.
498 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
499 // Handle 'dbg' as a special case since it is not stored in the hash table.
500 if (KindID == LLVMContext::MD_dbg)
501 return DbgLoc.getAsMDNode(getContext());
503 if (!hasMetadataHashEntry()) return 0;
505 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
506 assert(!Info.empty() && "bit out of sync with hash table");
508 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
510 if (I->first == KindID)
515 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
516 MDNode*> > &Result) const {
519 // Handle 'dbg' as a special case since it is not stored in the hash table.
520 if (!DbgLoc.isUnknown()) {
521 Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
522 DbgLoc.getAsMDNode(getContext())));
523 if (!hasMetadataHashEntry()) return;
526 assert(hasMetadataHashEntry() &&
527 getContext().pImpl->MetadataStore.count(this) &&
528 "Shouldn't have called this");
529 const LLVMContextImpl::MDMapTy &Info =
530 getContext().pImpl->MetadataStore.find(this)->second;
531 assert(!Info.empty() && "Shouldn't have called this");
533 Result.append(Info.begin(), Info.end());
535 // Sort the resulting array so it is stable.
536 if (Result.size() > 1)
537 array_pod_sort(Result.begin(), Result.end());
541 getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
542 MDNode*> > &Result) const {
544 assert(hasMetadataHashEntry() &&
545 getContext().pImpl->MetadataStore.count(this) &&
546 "Shouldn't have called this");
547 const LLVMContextImpl::MDMapTy &Info =
548 getContext().pImpl->MetadataStore.find(this)->second;
549 assert(!Info.empty() && "Shouldn't have called this");
551 Result.append(Info.begin(), Info.end());
553 // Sort the resulting array so it is stable.
554 if (Result.size() > 1)
555 array_pod_sort(Result.begin(), Result.end());
559 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
560 /// this instruction.
561 void Instruction::clearMetadataHashEntries() {
562 assert(hasMetadataHashEntry() && "Caller should check");
563 getContext().pImpl->MetadataStore.erase(this);
564 setHasMetadataHashEntry(false);