When promoting an alloca to registers discard any lifetime intrinsics.
[llvm/stm8.git] / lib / VMCore / Metadata.cpp
blobeb719e54b28927271ce5057e7ef2efc8050845f3
1 //===-- Metadata.cpp - Implement Metadata classes -------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Metadata classes.
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 "SymbolTableListTraitsImpl.h"
23 #include "llvm/Support/LeakDetector.h"
24 #include "llvm/Support/ValueHandle.h"
25 using namespace llvm;
27 //===----------------------------------------------------------------------===//
28 // MDString implementation.
31 MDString::MDString(LLVMContext &C, StringRef S)
32 : Value(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
34 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
35 LLVMContextImpl *pImpl = Context.pImpl;
36 StringMapEntry<MDString *> &Entry =
37 pImpl->MDStringCache.GetOrCreateValue(Str);
38 MDString *&S = Entry.getValue();
39 if (!S) S = new MDString(Context, Entry.getKey());
40 return S;
43 //===----------------------------------------------------------------------===//
44 // MDNodeOperand implementation.
47 // Use CallbackVH to hold MDNode operands.
48 namespace llvm {
49 class MDNodeOperand : public CallbackVH {
50 MDNode *Parent;
51 public:
52 MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
53 ~MDNodeOperand() {}
55 void set(Value *V) {
56 setValPtr(V);
59 virtual void deleted();
60 virtual void allUsesReplacedWith(Value *NV);
62 } // end namespace llvm.
65 void MDNodeOperand::deleted() {
66 Parent->replaceOperand(this, 0);
69 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
70 Parent->replaceOperand(this, NV);
75 //===----------------------------------------------------------------------===//
76 // MDNode implementation.
79 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
80 /// the end of the MDNode.
81 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
82 // Use <= instead of < to permit a one-past-the-end address.
83 assert(Op <= N->getNumOperands() && "Invalid operand number");
84 return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
87 MDNode::MDNode(LLVMContext &C, ArrayRef<Value*> Vals, bool isFunctionLocal)
88 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
89 NumOperands = Vals.size();
91 if (isFunctionLocal)
92 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
94 // Initialize the operand list, which is co-allocated on the end of the node.
95 unsigned i = 0;
96 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
97 Op != E; ++Op, ++i)
98 new (Op) MDNodeOperand(Vals[i], this);
102 /// ~MDNode - Destroy MDNode.
103 MDNode::~MDNode() {
104 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
105 "Not being destroyed through destroy()?");
106 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
107 if (isNotUniqued()) {
108 pImpl->NonUniquedMDNodes.erase(this);
109 } else {
110 pImpl->MDNodeSet.RemoveNode(this);
113 // Destroy the operands.
114 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
115 Op != E; ++Op)
116 Op->~MDNodeOperand();
119 static const Function *getFunctionForValue(Value *V) {
120 if (!V) return NULL;
121 if (Instruction *I = dyn_cast<Instruction>(V)) {
122 BasicBlock *BB = I->getParent();
123 return BB ? BB->getParent() : 0;
125 if (Argument *A = dyn_cast<Argument>(V))
126 return A->getParent();
127 if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
128 return BB->getParent();
129 if (MDNode *MD = dyn_cast<MDNode>(V))
130 return MD->getFunction();
131 return NULL;
134 #ifndef NDEBUG
135 static const Function *assertLocalFunction(const MDNode *N) {
136 if (!N->isFunctionLocal()) return 0;
138 // FIXME: This does not handle cyclic function local metadata.
139 const Function *F = 0, *NewF = 0;
140 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
141 if (Value *V = N->getOperand(i)) {
142 if (MDNode *MD = dyn_cast<MDNode>(V))
143 NewF = assertLocalFunction(MD);
144 else
145 NewF = getFunctionForValue(V);
147 if (F == 0)
148 F = NewF;
149 else
150 assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
152 return F;
154 #endif
156 // getFunction - If this metadata is function-local and recursively has a
157 // function-local operand, return the first such operand's parent function.
158 // Otherwise, return null. getFunction() should not be used for performance-
159 // critical code because it recursively visits all the MDNode's operands.
160 const Function *MDNode::getFunction() const {
161 #ifndef NDEBUG
162 return assertLocalFunction(this);
163 #endif
164 if (!isFunctionLocal()) return NULL;
165 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
166 if (const Function *F = getFunctionForValue(getOperand(i)))
167 return F;
168 return NULL;
171 // destroy - Delete this node. Only when there are no uses.
172 void MDNode::destroy() {
173 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
174 // Placement delete, the free the memory.
175 this->~MDNode();
176 free(this);
179 /// isFunctionLocalValue - Return true if this is a value that would require a
180 /// function-local MDNode.
181 static bool isFunctionLocalValue(Value *V) {
182 return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
183 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
186 MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Value*> Vals,
187 FunctionLocalness FL, bool Insert) {
188 LLVMContextImpl *pImpl = Context.pImpl;
190 // Add all the operand pointers. Note that we don't have to add the
191 // isFunctionLocal bit because that's implied by the operands.
192 // Note that if the operands are later nulled out, the node will be
193 // removed from the uniquing map.
194 FoldingSetNodeID ID;
195 for (unsigned i = 0; i != Vals.size(); ++i)
196 ID.AddPointer(Vals[i]);
198 void *InsertPoint;
199 MDNode *N = NULL;
201 if ((N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)))
202 return N;
204 bool isFunctionLocal = false;
205 switch (FL) {
206 case FL_Unknown:
207 for (unsigned i = 0; i != Vals.size(); ++i) {
208 Value *V = Vals[i];
209 if (!V) continue;
210 if (isFunctionLocalValue(V)) {
211 isFunctionLocal = true;
212 break;
215 break;
216 case FL_No:
217 isFunctionLocal = false;
218 break;
219 case FL_Yes:
220 isFunctionLocal = true;
221 break;
224 // Coallocate space for the node and Operands together, then placement new.
225 void *Ptr = malloc(sizeof(MDNode)+Vals.size()*sizeof(MDNodeOperand));
226 N = new (Ptr) MDNode(Context, Vals, isFunctionLocal);
228 // InsertPoint will have been set by the FindNodeOrInsertPos call.
229 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
231 return N;
234 MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Value*> Vals) {
235 return getMDNode(Context, Vals, FL_Unknown);
238 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context,
239 ArrayRef<Value*> Vals,
240 bool isFunctionLocal) {
241 return getMDNode(Context, Vals, isFunctionLocal ? FL_Yes : FL_No);
244 MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals) {
245 return getMDNode(Context, Vals, FL_Unknown, false);
248 MDNode *MDNode::getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals) {
249 MDNode *N =
250 (MDNode *)malloc(sizeof(MDNode)+Vals.size()*sizeof(MDNodeOperand));
251 N = new (N) MDNode(Context, Vals, FL_No);
252 N->setValueSubclassData(N->getSubclassDataFromValue() |
253 NotUniquedBit);
254 LeakDetector::addGarbageObject(N);
255 return N;
258 void MDNode::deleteTemporary(MDNode *N) {
259 assert(N->use_empty() && "Temporary MDNode has uses!");
260 assert(!N->getContext().pImpl->MDNodeSet.RemoveNode(N) &&
261 "Deleting a non-temporary uniqued node!");
262 assert(!N->getContext().pImpl->NonUniquedMDNodes.erase(N) &&
263 "Deleting a non-temporary non-uniqued node!");
264 assert((N->getSubclassDataFromValue() & NotUniquedBit) &&
265 "Temporary MDNode does not have NotUniquedBit set!");
266 assert((N->getSubclassDataFromValue() & DestroyFlag) == 0 &&
267 "Temporary MDNode has DestroyFlag set!");
268 LeakDetector::removeGarbageObject(N);
269 N->destroy();
272 /// getOperand - Return specified operand.
273 Value *MDNode::getOperand(unsigned i) const {
274 return *getOperandPtr(const_cast<MDNode*>(this), i);
277 void MDNode::Profile(FoldingSetNodeID &ID) const {
278 // Add all the operand pointers. Note that we don't have to add the
279 // isFunctionLocal bit because that's implied by the operands.
280 // Note that if the operands are later nulled out, the node will be
281 // removed from the uniquing map.
282 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
283 ID.AddPointer(getOperand(i));
286 void MDNode::setIsNotUniqued() {
287 setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
288 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
289 pImpl->NonUniquedMDNodes.insert(this);
292 // Replace value from this node's operand list.
293 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
294 Value *From = *Op;
296 // If is possible that someone did GV->RAUW(inst), replacing a global variable
297 // with an instruction or some other function-local object. If this is a
298 // non-function-local MDNode, it can't point to a function-local object.
299 // Handle this case by implicitly dropping the MDNode reference to null.
300 // Likewise if the MDNode is function-local but for a different function.
301 if (To && isFunctionLocalValue(To)) {
302 if (!isFunctionLocal())
303 To = 0;
304 else {
305 const Function *F = getFunction();
306 const Function *FV = getFunctionForValue(To);
307 // Metadata can be function-local without having an associated function.
308 // So only consider functions to have changed if non-null.
309 if (F && FV && F != FV)
310 To = 0;
314 if (From == To)
315 return;
317 // Update the operand.
318 Op->set(To);
320 // If this node is already not being uniqued (because one of the operands
321 // already went to null), then there is nothing else to do here.
322 if (isNotUniqued()) return;
324 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
326 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
327 // this node to remove it, so we don't care what state the operands are in.
328 pImpl->MDNodeSet.RemoveNode(this);
330 // If we are dropping an argument to null, we choose to not unique the MDNode
331 // anymore. This commonly occurs during destruction, and uniquing these
332 // brings little reuse. Also, this means we don't need to include
333 // isFunctionLocal bits in FoldingSetNodeIDs for MDNodes.
334 if (To == 0) {
335 setIsNotUniqued();
336 return;
339 // Now that the node is out of the folding set, get ready to reinsert it.
340 // First, check to see if another node with the same operands already exists
341 // in the set. If so, then this node is redundant.
342 FoldingSetNodeID ID;
343 Profile(ID);
344 void *InsertPoint;
345 if (MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)) {
346 replaceAllUsesWith(N);
347 destroy();
348 return;
351 // InsertPoint will have been set by the FindNodeOrInsertPos call.
352 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
354 // If this MDValue was previously function-local but no longer is, clear
355 // its function-local flag.
356 if (isFunctionLocal() && !isFunctionLocalValue(To)) {
357 bool isStillFunctionLocal = false;
358 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
359 Value *V = getOperand(i);
360 if (!V) continue;
361 if (isFunctionLocalValue(V)) {
362 isStillFunctionLocal = true;
363 break;
366 if (!isStillFunctionLocal)
367 setValueSubclassData(getSubclassDataFromValue() & ~FunctionLocalBit);
371 //===----------------------------------------------------------------------===//
372 // NamedMDNode implementation.
375 static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
376 return *(SmallVector<TrackingVH<MDNode>, 4>*)Operands;
379 NamedMDNode::NamedMDNode(const Twine &N)
380 : Name(N.str()), Parent(0),
381 Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {
384 NamedMDNode::~NamedMDNode() {
385 dropAllReferences();
386 delete &getNMDOps(Operands);
389 /// getNumOperands - Return number of NamedMDNode operands.
390 unsigned NamedMDNode::getNumOperands() const {
391 return (unsigned)getNMDOps(Operands).size();
394 /// getOperand - Return specified operand.
395 MDNode *NamedMDNode::getOperand(unsigned i) const {
396 assert(i < getNumOperands() && "Invalid Operand number!");
397 return dyn_cast<MDNode>(&*getNMDOps(Operands)[i]);
400 /// addOperand - Add metadata Operand.
401 void NamedMDNode::addOperand(MDNode *M) {
402 assert(!M->isFunctionLocal() &&
403 "NamedMDNode operands must not be function-local!");
404 getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
407 /// eraseFromParent - Drop all references and remove the node from parent
408 /// module.
409 void NamedMDNode::eraseFromParent() {
410 getParent()->eraseNamedMetadata(this);
413 /// dropAllReferences - Remove all uses and clear node vector.
414 void NamedMDNode::dropAllReferences() {
415 getNMDOps(Operands).clear();
418 /// getName - Return a constant reference to this named metadata's name.
419 StringRef NamedMDNode::getName() const {
420 return StringRef(Name);
423 //===----------------------------------------------------------------------===//
424 // Instruction Metadata method implementations.
427 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
428 if (Node == 0 && !hasMetadata()) return;
429 setMetadata(getContext().getMDKindID(Kind), Node);
432 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
433 return getMetadataImpl(getContext().getMDKindID(Kind));
436 /// setMetadata - Set the metadata of of the specified kind to the specified
437 /// node. This updates/replaces metadata if already present, or removes it if
438 /// Node is null.
439 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
440 if (Node == 0 && !hasMetadata()) return;
442 // Handle 'dbg' as a special case since it is not stored in the hash table.
443 if (KindID == LLVMContext::MD_dbg) {
444 DbgLoc = DebugLoc::getFromDILocation(Node);
445 return;
448 // Handle the case when we're adding/updating metadata on an instruction.
449 if (Node) {
450 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
451 assert(!Info.empty() == hasMetadataHashEntry() &&
452 "HasMetadata bit is wonked");
453 if (Info.empty()) {
454 setHasMetadataHashEntry(true);
455 } else {
456 // Handle replacement of an existing value.
457 for (unsigned i = 0, e = Info.size(); i != e; ++i)
458 if (Info[i].first == KindID) {
459 Info[i].second = Node;
460 return;
464 // No replacement, just add it to the list.
465 Info.push_back(std::make_pair(KindID, Node));
466 return;
469 // Otherwise, we're removing metadata from an instruction.
470 assert(hasMetadataHashEntry() &&
471 getContext().pImpl->MetadataStore.count(this) &&
472 "HasMetadata bit out of date!");
473 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
475 // Common case is removing the only entry.
476 if (Info.size() == 1 && Info[0].first == KindID) {
477 getContext().pImpl->MetadataStore.erase(this);
478 setHasMetadataHashEntry(false);
479 return;
482 // Handle removal of an existing value.
483 for (unsigned i = 0, e = Info.size(); i != e; ++i)
484 if (Info[i].first == KindID) {
485 Info[i] = Info.back();
486 Info.pop_back();
487 assert(!Info.empty() && "Removing last entry should be handled above");
488 return;
490 // Otherwise, removing an entry that doesn't exist on the instruction.
493 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
494 // Handle 'dbg' as a special case since it is not stored in the hash table.
495 if (KindID == LLVMContext::MD_dbg)
496 return DbgLoc.getAsMDNode(getContext());
498 if (!hasMetadataHashEntry()) return 0;
500 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
501 assert(!Info.empty() && "bit out of sync with hash table");
503 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
504 I != E; ++I)
505 if (I->first == KindID)
506 return I->second;
507 return 0;
510 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
511 MDNode*> > &Result) const {
512 Result.clear();
514 // Handle 'dbg' as a special case since it is not stored in the hash table.
515 if (!DbgLoc.isUnknown()) {
516 Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
517 DbgLoc.getAsMDNode(getContext())));
518 if (!hasMetadataHashEntry()) return;
521 assert(hasMetadataHashEntry() &&
522 getContext().pImpl->MetadataStore.count(this) &&
523 "Shouldn't have called this");
524 const LLVMContextImpl::MDMapTy &Info =
525 getContext().pImpl->MetadataStore.find(this)->second;
526 assert(!Info.empty() && "Shouldn't have called this");
528 Result.append(Info.begin(), Info.end());
530 // Sort the resulting array so it is stable.
531 if (Result.size() > 1)
532 array_pod_sort(Result.begin(), Result.end());
535 void Instruction::
536 getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
537 MDNode*> > &Result) const {
538 Result.clear();
539 assert(hasMetadataHashEntry() &&
540 getContext().pImpl->MetadataStore.count(this) &&
541 "Shouldn't have called this");
542 const LLVMContextImpl::MDMapTy &Info =
543 getContext().pImpl->MetadataStore.find(this)->second;
544 assert(!Info.empty() && "Shouldn't have called this");
546 Result.append(Info.begin(), Info.end());
548 // Sort the resulting array so it is stable.
549 if (Result.size() > 1)
550 array_pod_sort(Result.begin(), Result.end());
554 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
555 /// this instruction.
556 void Instruction::clearMetadataHashEntries() {
557 assert(hasMetadataHashEntry() && "Caller should check");
558 getContext().pImpl->MetadataStore.erase(this);
559 setHasMetadataHashEntry(false);