a4a0134f8978281c2cdea76704a9dd5521e6d427
[oota-llvm.git] / lib / VMCore / SymbolTable.cpp
1 //===-- SymbolTable.cpp - Implement the SymbolTable class -----------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and revised by Reid
6 // Spencer. It is distributed under the University of Illinois Open Source 
7 // License. See LICENSE.TXT for details.
8 // 
9 //===----------------------------------------------------------------------===//
10 //
11 // This file implements the SymbolTable class for the VMCore library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/SymbolTable.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Module.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include <algorithm>
20 #include <iostream>
21
22 using namespace llvm;
23
24 #define DEBUG_SYMBOL_TABLE 0
25 #define DEBUG_ABSTYPE 0
26
27 SymbolTable::~SymbolTable() {
28   // Drop all abstract type references in the type plane...
29   for (type_iterator TI = tmap.begin(), TE = tmap.end(); TI != TE; ++TI) {
30     if (TI->second->isAbstract())   // If abstract, drop the reference...
31       cast<DerivedType>(TI->second)->removeAbstractTypeUser(this);
32   }
33
34  // TODO: FIXME: BIG ONE: This doesn't unreference abstract types for the 
35  // planes that could still have entries!
36
37 #ifndef NDEBUG   // Only do this in -g mode...
38   bool LeftoverValues = true;
39   for (plane_iterator PI = pmap.begin(); PI != pmap.end(); ++PI) {
40     for (value_iterator VI = PI->second.begin(); VI != PI->second.end(); ++VI)
41       if (!isa<Constant>(VI->second) ) {
42         std::cerr << "Value still in symbol table! Type = '"
43                   << PI->first->getDescription() << "' Name = '"
44                   << VI->first << "'\n";
45         LeftoverValues = false;
46       }
47   }
48   
49   assert(LeftoverValues && "Values remain in symbol table!");
50 #endif
51 }
52
53 // getUniqueName - Given a base name, return a string that is either equal to
54 // it (or derived from it) that does not already occur in the symbol table for
55 // the specified type.
56 //
57 std::string SymbolTable::getUniqueName(const Type *Ty,
58                                        const std::string &BaseName) const {
59   // Find the plane
60   plane_const_iterator PI = pmap.find(Ty);
61   if (PI == pmap.end()) return BaseName;
62
63   std::string TryName = BaseName;
64   const ValueMap& vmap = PI->second;
65   value_const_iterator End = vmap.end();
66
67   // See if the name exists
68   while (vmap.find(TryName) != End)            // Loop until we find a free
69     TryName = BaseName + utostr(++LastUnique); // name in the symbol table
70   return TryName;
71 }
72
73
74 // lookup a value - Returns null on failure...
75 Value *SymbolTable::lookup(const Type *Ty, const std::string &Name) const {
76   plane_const_iterator PI = pmap.find(Ty);
77   if (PI != pmap.end()) {                // We have symbols in that plane.
78     value_const_iterator VI = PI->second.find(Name);
79     if (VI != PI->second.end())          // and the name is in our hash table.
80       return VI->second;
81   }
82   return 0;
83 }
84
85
86 // lookup a type by name - returns null on failure
87 Type* SymbolTable::lookupType( const std::string& Name ) const {
88   type_const_iterator TI = tmap.find( Name );
89   if ( TI != tmap.end() )
90     return const_cast<Type*>(TI->second);
91   return 0;
92 }
93
94 // Remove a value
95 void SymbolTable::remove(Value *N) {
96   assert(N->hasName() && "Value doesn't have name!");
97   if (InternallyInconsistent) return;
98
99   plane_iterator PI = pmap.find(N->getType());
100   assert(PI != pmap.end() &&
101          "Trying to remove a value that doesn't have a type plane yet!");
102   removeEntry(PI, PI->second.find(N->getName()));
103 }
104
105 /// changeName - Given a value with a non-empty name, remove its existing entry
106 /// from the symbol table and insert a new one for Name.  This is equivalent to
107 /// doing "remove(V), V->Name = Name, insert(V)", but is faster, and will not
108 /// temporarily remove the symbol table plane if V is the last value in the
109 /// symtab with that name (which could invalidate iterators to that plane).
110 void SymbolTable::changeName(Value *V, const std::string &name) {
111   assert(!V->getName().empty() && !name.empty() && V->getName() != name &&
112          "Illegal use of this method!");
113
114   plane_iterator PI = pmap.find(V->getType());
115   assert(PI != pmap.end() && "Value doesn't have an entry in this table?");
116   ValueMap &VM = PI->second;
117
118   value_iterator VI;
119
120   if (!InternallyInconsistent) {
121     VI = VM.find(V->getName());
122     assert(VI != VM.end() && "Value does have an entry in this table?");
123
124     // Remove the old entry.
125     VM.erase(VI);
126   }
127
128   // See if we can insert the new name.
129   VI = VM.lower_bound(name);
130
131   // Is there a naming conflict?
132   if (VI != VM.end() && VI->first == name) {
133     V->Name = getUniqueName(V->getType(), name);
134     VM.insert(make_pair(V->Name, V));
135   } else {
136     V->Name = name;
137     VM.insert(VI, make_pair(name, V));
138   }
139 }
140
141
142 // removeEntry - Remove a value from the symbol table...
143 Value *SymbolTable::removeEntry(plane_iterator Plane, value_iterator Entry) {
144   if (InternallyInconsistent) return 0;
145   assert(Plane != pmap.end() &&
146          Entry != Plane->second.end() && "Invalid entry to remove!");
147
148   Value *Result = Entry->second;
149 #if DEBUG_SYMBOL_TABLE
150   dump();
151   std::cerr << " Removing Value: " << Result->getName() << "\n";
152 #endif
153
154   // Remove the value from the plane...
155   Plane->second.erase(Entry);
156
157   // If the plane is empty, remove it now!
158   if (Plane->second.empty()) {
159     // If the plane represented an abstract type that we were interested in,
160     // unlink ourselves from this plane.
161     //
162     if (Plane->first->isAbstract()) {
163 #if DEBUG_ABSTYPE
164       std::cerr << "Plane Empty: Removing type: "
165                 << Plane->first->getDescription() << "\n";
166 #endif
167       cast<DerivedType>(Plane->first)->removeAbstractTypeUser(this);
168     }
169
170     pmap.erase(Plane);
171   }
172   return Result;
173 }
174
175
176 // remove - Remove a type
177 void SymbolTable::remove(const Type* Ty ) {
178   type_iterator TI = this->type_begin();
179   type_iterator TE = this->type_end();
180
181   // Search for the entry
182   while ( TI != TE && TI->second != Ty )
183     ++TI;
184
185   if ( TI != TE )
186     this->removeEntry( TI );
187 }
188
189
190 // removeEntry - Remove a type from the symbol table...
191 Type* SymbolTable::removeEntry(type_iterator Entry) {
192   if (InternallyInconsistent) return 0;
193   assert( Entry != tmap.end() && "Invalid entry to remove!");
194
195   const Type* Result = Entry->second;
196
197 #if DEBUG_SYMBOL_TABLE
198   dump();
199   std::cerr << " Removing Value: " << Result->getName() << "\n";
200 #endif
201
202   tmap.erase(Entry);
203
204   // If we are removing an abstract type, remove the symbol table from it's use
205   // list...
206   if (Result->isAbstract()) {
207 #if DEBUG_ABSTYPE
208     std::cerr << "Removing abstract type from symtab" << Result->getDescription()<<"\n";
209 #endif
210     cast<DerivedType>(Result)->removeAbstractTypeUser(this);
211   }
212
213   return const_cast<Type*>(Result);
214 }
215
216
217 // insertEntry - Insert a value into the symbol table with the specified name.
218 void SymbolTable::insertEntry(const std::string &Name, const Type *VTy,
219                               Value *V) {
220   plane_iterator PI = pmap.find(VTy);   // Plane iterator
221   value_iterator VI;                    // Actual value iterator
222   ValueMap *VM;                         // The plane we care about.
223
224 #if DEBUG_SYMBOL_TABLE
225   dump();
226   std::cerr << " Inserting definition: " << Name << ": " 
227             << VTy->getDescription() << "\n";
228 #endif
229
230   if (PI == pmap.end()) {      // Not in collection yet... insert dummy entry
231     // Insert a new empty element.  I points to the new elements.
232     VM = &pmap.insert(make_pair(VTy, ValueMap())).first->second;
233     VI = VM->end();
234
235     // Check to see if the type is abstract.  If so, it might be refined in the
236     // future, which would cause the plane of the old type to get merged into
237     // a new type plane.
238     //
239     if (VTy->isAbstract()) {
240       cast<DerivedType>(VTy)->addAbstractTypeUser(this);
241 #if DEBUG_ABSTYPE
242       std::cerr << "Added abstract type value: " << VTy->getDescription()
243                 << "\n";
244 #endif
245     }
246
247   } else {
248     // Check to see if there is a naming conflict.  If so, rename this value!
249     VM = &PI->second;
250     VI = VM->lower_bound(Name);
251     if (VI != VM->end() && VI->first == Name) {
252       std::string UniqueName = getUniqueName(VTy, Name);
253       assert(InternallyInconsistent == false &&
254              "Infinite loop inserting value!");
255       V->Name = UniqueName;
256       VM->insert(VI, make_pair(UniqueName, V));
257       return;
258     }
259   }
260
261   VM->insert(VI, make_pair(Name, V));
262 }
263
264
265 // insertEntry - Insert a value into the symbol table with the specified
266 // name...
267 //
268 void SymbolTable::insertEntry(const std::string& Name, const Type* T) {
269
270   // Check to see if there is a naming conflict.  If so, rename this type!
271   std::string UniqueName = Name;
272   if (lookupType(Name))
273     UniqueName = getUniqueName(T, Name);
274
275 #if DEBUG_SYMBOL_TABLE
276   dump();
277   std::cerr << " Inserting type: " << UniqueName << ": " 
278             << T->getDescription() << "\n";
279 #endif
280
281   // Insert the tmap entry
282   tmap.insert(make_pair(UniqueName, T));
283
284   // If we are adding an abstract type, add the symbol table to it's use list.
285   if (T->isAbstract()) {
286     cast<DerivedType>(T)->addAbstractTypeUser(this);
287 #if DEBUG_ABSTYPE
288     std::cerr << "Added abstract type to ST: " << T->getDescription() << "\n";
289 #endif
290   }
291 }
292
293 // Strip the symbol table of its names.
294 bool SymbolTable::strip() {
295   bool RemovedSymbol = false;
296   for (plane_iterator I = pmap.begin(); I != pmap.end();) {
297     // Removing items from the plane can cause the plane itself to get deleted.
298     // If this happens, make sure we incremented our plane iterator already!
299     ValueMap &Plane = (I++)->second;
300     value_iterator B = Plane.begin(), Bend = Plane.end();
301     while (B != Bend) {   // Found nonempty type plane!
302       Value *V = B->second;
303       if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()) {
304         // Set name to "", removing from symbol table!
305         V->setName("");
306         RemovedSymbol = true;
307       }
308       ++B;
309     }
310   }
311
312   for (type_iterator TI = tmap.begin(); TI != tmap.end(); ) {
313     const Type* T = (TI++)->second;
314     remove(T);
315     RemovedSymbol = true;
316   }
317  
318   return RemovedSymbol;
319 }
320
321
322 // This function is called when one of the types in the type plane are refined
323 void SymbolTable::refineAbstractType(const DerivedType *OldType,
324                                      const Type *NewType) {
325
326   // Search to see if we have any values of the type Oldtype.  If so, we need to
327   // move them into the newtype plane...
328   plane_iterator PI = pmap.find(OldType);
329   if (PI != pmap.end()) {
330     // Get a handle to the new type plane...
331     plane_iterator NewTypeIt = pmap.find(NewType);
332     if (NewTypeIt == pmap.end()) {      // If no plane exists, add one
333       NewTypeIt = pmap.insert(make_pair(NewType, ValueMap())).first;
334       
335       if (NewType->isAbstract()) {
336         cast<DerivedType>(NewType)->addAbstractTypeUser(this);
337 #if DEBUG_ABSTYPE
338         std::cerr << "[Added] refined to abstype: " << NewType->getDescription()
339                   << "\n";
340 #endif
341       }
342     }
343
344     ValueMap &NewPlane = NewTypeIt->second;
345     ValueMap &OldPlane = PI->second;
346     while (!OldPlane.empty()) {
347       std::pair<const std::string, Value*> V = *OldPlane.begin();
348
349       // Check to see if there is already a value in the symbol table that this
350       // would collide with.
351       value_iterator VI = NewPlane.find(V.first);
352       if (VI != NewPlane.end() && VI->second == V.second) {
353         // No action
354
355       } else if (VI != NewPlane.end()) {
356         // The only thing we are allowing for now is two external global values
357         // folded into one.
358         //
359         GlobalValue *ExistGV = dyn_cast<GlobalValue>(VI->second);
360         GlobalValue *NewGV = dyn_cast<GlobalValue>(V.second);
361
362         if (ExistGV && NewGV) {
363           assert((ExistGV->isExternal() || NewGV->isExternal()) &&
364                  "Two planes folded together with overlapping value names!");
365
366           // Make sure that ExistGV is the one we want to keep!
367           if (!NewGV->isExternal())
368             std::swap(NewGV, ExistGV);
369
370           // Ok we have two external global values.  Make all uses of the new
371           // one use the old one...
372           NewGV->uncheckedReplaceAllUsesWith(ExistGV);
373           
374           // Now we just convert it to an unnamed method... which won't get
375           // added to our symbol table.  The problem is that if we call
376           // setName on the method that it will try to remove itself from
377           // the symbol table and die... because it's not in the symtab
378           // right now.  To fix this, we have an internally consistent flag
379           // that turns remove into a noop.  Thus the name will get null'd
380           // out, but the symbol table won't get upset.
381           //
382           assert(InternallyInconsistent == false &&
383                  "Symbol table already inconsistent!");
384
385           // Update NewGV's name, we're about the remove it from the symbol
386           // table.
387           NewGV->Name = "";
388
389           // Now we can remove this global from the module entirely...
390           Module *M = NewGV->getParent();
391           if (Function *F = dyn_cast<Function>(NewGV))
392             M->getFunctionList().remove(F);
393           else
394             M->getGlobalList().remove(cast<GlobalVariable>(NewGV));
395           delete NewGV;
396         } else {
397           // If they are not global values, they must be just random values who
398           // happen to conflict now that types have been resolved.  If this is
399           // the case, reinsert the value into the new plane, allowing it to get
400           // renamed.
401           assert(V.second->getType() == NewType &&"Type resolution is broken!");
402           insert(V.second);
403         }
404       } else {
405         insertEntry(V.first, NewType, V.second);
406       }
407       // Remove the item from the old type plane
408       OldPlane.erase(OldPlane.begin());
409     }
410
411     // Ok, now we are not referencing the type anymore... take me off your user
412     // list please!
413 #if DEBUG_ABSTYPE
414     std::cerr << "Removing type " << OldType->getDescription() << "\n";
415 #endif
416     OldType->removeAbstractTypeUser(this);
417
418     // Remove the plane that is no longer used
419     pmap.erase(PI);
420   }
421
422   // Loop over all of the types in the symbol table, replacing any references
423   // to OldType with references to NewType.  Note that there may be multiple
424   // occurrences, and although we only need to remove one at a time, it's
425   // faster to remove them all in one pass.
426   //
427   for (type_iterator I = type_begin(), E = type_end(); I != E; ++I) {
428     if (I->second == (Type*)OldType) {  // FIXME when Types aren't const.
429 #if DEBUG_ABSTYPE
430       std::cerr << "Removing type " << OldType->getDescription() << "\n";
431 #endif
432       OldType->removeAbstractTypeUser(this);
433         
434       I->second = (Type*)NewType;  // TODO FIXME when types aren't const
435       if (NewType->isAbstract()) {
436 #if DEBUG_ABSTYPE
437         std::cerr << "Added type " << NewType->getDescription() << "\n";
438 #endif
439         cast<DerivedType>(NewType)->addAbstractTypeUser(this);
440       }
441     }
442   }
443 }
444
445
446 // Handle situation where type becomes Concreate from Abstract
447 void SymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
448   plane_iterator PI = pmap.find(AbsTy);
449
450   // If there are any values in the symbol table of this type, then the type
451   // plane is a use of the abstract type which must be dropped.
452   if (PI != pmap.end())
453     AbsTy->removeAbstractTypeUser(this);
454
455   // Loop over all of the types in the symbol table, dropping any abstract
456   // type user entries for AbsTy which occur because there are names for the
457   // type.
458   for (type_iterator TI = type_begin(), TE = type_end(); TI != TE; ++TI)
459     if (TI->second == (Type*)AbsTy)   // FIXME when Types aren't const.
460       AbsTy->removeAbstractTypeUser(this);
461 }
462
463 static void DumpVal(const std::pair<const std::string, Value *> &V) {
464   std::cerr << "  '" << V.first << "' = ";
465   V.second->dump();
466   std::cerr << "\n";
467 }
468
469 static void DumpPlane(const std::pair<const Type *,
470                                       std::map<const std::string, Value *> >&P){
471   P.first->dump();
472   std::cerr << "\n";
473   for_each(P.second.begin(), P.second.end(), DumpVal);
474 }
475
476 static void DumpTypes(const std::pair<const std::string, const Type*>& T ) {
477   std::cerr << "  '" << T.first << "' = ";
478   T.second->dump();
479   std::cerr << "\n";
480 }
481
482 void SymbolTable::dump() const {
483   std::cerr << "Symbol table dump:\n  Plane:";
484   for_each(pmap.begin(), pmap.end(), DumpPlane);
485   std::cerr << "  Types: ";
486   for_each(tmap.begin(), tmap.end(), DumpTypes);
487 }
488
489 // vim: sw=2 ai