Banish ConstantsLock. It's serving no purpose other than slowing things down
[oota-llvm.git] / lib / VMCore / Metadata.cpp
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.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LLVMContextImpl.h"
15 #include "llvm/Metadata.h"
16 #include "llvm/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/Instruction.h"
19 #include "SymbolTableListTraitsImpl.h"
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 // MetadataBase implementation.
24 //
25
26 /// resizeOperands - Metadata keeps track of other metadata uses using 
27 /// OperandList. Resize this list to hold anticipated number of metadata
28 /// operands.
29 void MetadataBase::resizeOperands(unsigned NumOps) {
30   unsigned e = getNumOperands();
31   if (NumOps == 0) {
32     NumOps = e*2;
33     if (NumOps < 2) NumOps = 2;  
34   } else if (NumOps > NumOperands) {
35     // No resize needed.
36     if (ReservedSpace >= NumOps) return;
37   } else if (NumOps == NumOperands) {
38     if (ReservedSpace == NumOps) return;
39   } else {
40     return;
41   }
42
43   ReservedSpace = NumOps;
44   Use *OldOps = OperandList;
45   Use *NewOps = allocHungoffUses(NumOps);
46   std::copy(OldOps, OldOps + e, NewOps);
47   OperandList = NewOps;
48   if (OldOps) Use::zap(OldOps, OldOps + e, true);
49 }
50 //===----------------------------------------------------------------------===//
51 // MDString implementation.
52 //
53 MDString *MDString::get(LLVMContext &Context, const StringRef &Str) {
54   LLVMContextImpl *pImpl = Context.pImpl;
55   StringMapEntry<MDString *> &Entry = 
56     pImpl->MDStringCache.GetOrCreateValue(Str);
57   MDString *&S = Entry.getValue();
58   if (S) return S;
59   
60   return S = new MDString(Context, Entry.getKeyData(), Entry.getKeyLength());
61 }
62
63 //===----------------------------------------------------------------------===//
64 // MDNode implementation.
65 //
66 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals)
67   : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
68   NumOperands = 0;
69   resizeOperands(NumVals);
70   for (unsigned i = 0; i != NumVals; ++i) {
71     // Only record metadata uses.
72     if (MetadataBase *MB = dyn_cast_or_null<MetadataBase>(Vals[i]))
73       OperandList[NumOperands++] = MB;
74     else if(Vals[i] && 
75             Vals[i]->getType()->getTypeID() == Type::MetadataTyID)
76       OperandList[NumOperands++] = Vals[i];
77     Node.push_back(ElementVH(Vals[i], this));
78   }
79 }
80
81 void MDNode::Profile(FoldingSetNodeID &ID) const {
82   for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
83     ID.AddPointer(*I);
84 }
85
86 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
87   LLVMContextImpl *pImpl = Context.pImpl;
88   FoldingSetNodeID ID;
89   for (unsigned i = 0; i != NumVals; ++i)
90     ID.AddPointer(Vals[i]);
91
92   void *InsertPoint;
93   MDNode *N;
94   {
95     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
96   }  
97   if (N) return N;
98   
99   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
100   if (!N) {
101     // InsertPoint will have been set by the FindNodeOrInsertPos call.
102     N = new MDNode(Context, Vals, NumVals);
103     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
104   }
105
106   return N;
107 }
108
109 /// dropAllReferences - Remove all uses and clear node vector.
110 void MDNode::dropAllReferences() {
111   User::dropAllReferences();
112   Node.clear();
113 }
114
115 MDNode::~MDNode() {
116   {
117     LLVMContextImpl *pImpl = getType()->getContext().pImpl;
118     pImpl->MDNodeSet.RemoveNode(this);
119   }
120   dropAllReferences();
121 }
122
123 // Replace value from this node's element list.
124 void MDNode::replaceElement(Value *From, Value *To) {
125   if (From == To || !getType())
126     return;
127   LLVMContext &Context = getType()->getContext();
128   LLVMContextImpl *pImpl = Context.pImpl;
129
130   // Find value. This is a linear search, do something if it consumes 
131   // lot of time. It is possible that to have multiple instances of
132   // From in this MDNode's element list.
133   SmallVector<unsigned, 4> Indexes;
134   unsigned Index = 0;
135   for (SmallVector<ElementVH, 4>::iterator I = Node.begin(),
136          E = Node.end(); I != E; ++I, ++Index) {
137     Value *V = *I;
138     if (V && V == From) 
139       Indexes.push_back(Index);
140   }
141
142   if (Indexes.empty())
143     return;
144
145   // Remove "this" from the context map. 
146   pImpl->MDNodeSet.RemoveNode(this);
147
148   // MDNode only lists metadata elements in operand list, because MDNode
149   // used by MDNode is considered a valid use. However on the side, MDNode
150   // using a non-metadata value is not considered a "use" of non-metadata
151   // value.
152   SmallVector<unsigned, 4> OpIndexes;
153   unsigned OpIndex = 0;
154   for (User::op_iterator OI = op_begin(), OE = op_end();
155        OI != OE; ++OI, OpIndex++) {
156     if (*OI == From)
157       OpIndexes.push_back(OpIndex);
158   }
159   if (MetadataBase *MDTo = dyn_cast_or_null<MetadataBase>(To)) {
160     for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
161            OE = OpIndexes.end(); OI != OE; ++OI)
162       setOperand(*OI, MDTo);
163   } else {
164     for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
165            OE = OpIndexes.end(); OI != OE; ++OI)
166       setOperand(*OI, 0);
167   }
168
169   // Replace From element(s) in place.
170   for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); 
171        I != E; ++I) {
172     unsigned Index = *I;
173     Node[Index] = ElementVH(To, this);
174   }
175
176   // Insert updated "this" into the context's folding node set.
177   // If a node with same element list already exist then before inserting 
178   // updated "this" into the folding node set, replace all uses of existing 
179   // node with updated "this" node.
180   FoldingSetNodeID ID;
181   Profile(ID);
182   void *InsertPoint;
183   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
184
185   if (N) {
186     N->replaceAllUsesWith(this);
187     delete N;
188     N = 0;
189   }
190
191   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
192   if (!N) {
193     // InsertPoint will have been set by the FindNodeOrInsertPos call.
194     N = this;
195     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
196   }
197 }
198
199 //===----------------------------------------------------------------------===//
200 // NamedMDNode implementation.
201 //
202 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
203                          MetadataBase *const *MDs, 
204                          unsigned NumMDs, Module *ParentModule)
205   : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
206   setName(N);
207   NumOperands = 0;
208   resizeOperands(NumMDs);
209
210   for (unsigned i = 0; i != NumMDs; ++i) {
211     if (MDs[i])
212       OperandList[NumOperands++] = MDs[i];
213     Node.push_back(WeakMetadataVH(MDs[i]));
214   }
215   if (ParentModule)
216     ParentModule->getNamedMDList().push_back(this);
217 }
218
219 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
220   assert(NMD && "Invalid source NamedMDNode!");
221   SmallVector<MetadataBase *, 4> Elems;
222   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
223     Elems.push_back(NMD->getElement(i));
224   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
225                          Elems.data(), Elems.size(), M);
226 }
227
228 /// eraseFromParent - Drop all references and remove the node from parent
229 /// module.
230 void NamedMDNode::eraseFromParent() {
231   getParent()->getNamedMDList().erase(this);
232 }
233
234 /// dropAllReferences - Remove all uses and clear node vector.
235 void NamedMDNode::dropAllReferences() {
236   User::dropAllReferences();
237   Node.clear();
238 }
239
240 NamedMDNode::~NamedMDNode() {
241   dropAllReferences();
242 }
243
244 //===----------------------------------------------------------------------===//
245 // MetadataContext implementation.
246 //
247
248 /// RegisterMDKind - Register a new metadata kind and return its ID.
249 /// A metadata kind can be registered only once. 
250 unsigned MetadataContext::RegisterMDKind(const char *Name) {
251   assert(validName(Name) && "Invalid custome metadata name!");
252   unsigned Count = MDHandlerNames.size();
253   assert(MDHandlerNames.find(Name) == MDHandlerNames.end() 
254          && "Already registered MDKind!");
255   MDHandlerNames[Name] = Count + 1;
256   return Count + 1;
257 }
258
259 /// validName - Return true if Name is a valid custom metadata handler name.
260 bool MetadataContext::validName(const char *Name) {
261   if (!Name)
262     return false;
263
264   if (!isalpha(*Name))
265     return false;
266
267   unsigned Length = strlen(Name);  
268   unsigned Count = 1;
269   ++Name;
270   while (Name &&
271          (isalnum(*Name) || *Name == '_' || *Name == '-' || *Name == '.')) {
272     ++Name;
273     ++Count;
274   }
275   if (Length != Count)
276     return false;
277   return true;
278 }
279
280 /// getMDKind - Return metadata kind. If the requested metadata kind
281 /// is not registered then return 0.
282 unsigned MetadataContext::getMDKind(const char *Name) {
283   assert(validName(Name) && "Invalid custome metadata name!");
284   StringMap<unsigned>::iterator I = MDHandlerNames.find(Name);
285   if (I == MDHandlerNames.end())
286     return 0;
287
288   return I->getValue();
289 }
290
291 /// addMD - Attach the metadata of given kind with an Instruction.
292 void MetadataContext::addMD(unsigned MDKind, MDNode *Node, Instruction *Inst) {
293   assert(Node && "Invalid null MDNode");
294   Inst->HasMetadata = true;
295   MDStoreTy::iterator I = MetadataStore.find(Inst);
296   if (I == MetadataStore.end()) {
297     MDMapTy Info;
298     Info.push_back(std::make_pair(MDKind, Node));
299     MetadataStore.insert(std::make_pair(Inst, Info));
300     return;
301   }
302
303   MDMapTy &Info = I->second;
304   // If there is an entry for this MDKind then replace it.
305   for (unsigned i = 0, e = Info.size(); i != e; ++i) {
306     MDPairTy &P = Info[i];
307     if (P.first == MDKind) {
308       Info[i] = std::make_pair(MDKind, Node);
309       return;
310     }
311   }
312
313   // Otherwise add a new entry.
314   Info.push_back(std::make_pair(MDKind, Node));
315   return;
316 }
317
318 /// removeMD - Remove metadata of given kind attached with an instuction.
319 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
320   MDStoreTy::iterator I = MetadataStore.find(Inst);
321   if (I == MetadataStore.end())
322     return;
323
324   MDMapTy &Info = I->second;
325   for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
326     MDPairTy &P = *MI;
327     if (P.first == Kind) {
328       Info.erase(MI);
329       return;
330     }
331   }
332
333   return;
334 }
335   
336 /// removeMDs - Remove all metadata attached with an instruction.
337 void MetadataContext::removeMDs(const Instruction *Inst) {
338   // Find Metadata handles for this instruction.
339   MDStoreTy::iterator I = MetadataStore.find(Inst);
340   assert(I != MetadataStore.end() && "Invalid custom metadata info!");
341   MDMapTy &Info = I->second;
342   
343   // FIXME : Give all metadata handlers a chance to adjust.
344   
345   // Remove the entries for this instruction.
346   Info.clear();
347   MetadataStore.erase(I);
348 }
349
350 /// copyMD - If metadata is attached with Instruction In1 then attach
351 /// the same metadata to In2.
352 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
353   assert(In1 && In2 && "Invalid instruction!");
354    MDStoreTy::iterator I = MetadataStore.find(In1);
355   if (I == MetadataStore.end())
356     return;
357
358   MDMapTy &In1Info = I->second;
359   MDMapTy In2Info;
360   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
361     if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
362       addMD(I->first, MD, In2);
363 }
364
365 /// getMD - Get the metadata of given kind attached with an Instruction.
366 /// If the metadata is not found then return 0.
367 MDNode *MetadataContext::getMD(unsigned MDKind, const Instruction *Inst) {
368   MDStoreTy::iterator I = MetadataStore.find(Inst);
369   if (I == MetadataStore.end())
370     return NULL;
371   
372   MDMapTy &Info = I->second;
373   for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
374     if (I->first == MDKind)
375       return dyn_cast_or_null<MDNode>(I->second);
376   return NULL;
377 }
378
379 /// getMDs - Get the metadata attached with an Instruction.
380 const MetadataContext::MDMapTy *
381 MetadataContext::getMDs(const Instruction *Inst) {
382   MDStoreTy::iterator I = MetadataStore.find(Inst);
383   if (I == MetadataStore.end())
384     return NULL;
385   
386   return &I->second;
387 }
388
389 /// getHandlerNames - Get handler names. This is used by bitcode
390 /// writer.
391 const StringMap<unsigned> *MetadataContext::getHandlerNames() {
392   return &MDHandlerNames;
393 }
394
395 /// ValueIsCloned - This handler is used to update metadata store
396 /// when In1 is cloned to create In2.
397 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
398   // Find Metadata handles for In1.
399   MDStoreTy::iterator I = MetadataStore.find(In1);
400   assert(I != MetadataStore.end() && "Invalid custom metadata info!");
401
402   // FIXME : Give all metadata handlers a chance to adjust.
403
404   MDMapTy &In1Info = I->second;
405   MDMapTy In2Info;
406   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
407     if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
408       addMD(I->first, MD, In2);
409 }
410
411 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
412 /// V2.
413 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
414   Instruction *I1 = dyn_cast<Instruction>(V1);
415   Instruction *I2 = dyn_cast<Instruction>(V2);
416   if (!I1 || !I2)
417     return;
418
419   // FIXME : Give custom handlers a chance to override this.
420   ValueIsCloned(I1, I2);
421 }
422