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