More symbol table bugfixes that are impossible to track down. Goody
[oota-llvm.git] / lib / VMCore / SymbolTable.cpp
1 //===-- SymbolTable.cpp - Implement the SymbolTable class -------------------=//
2 //
3 // This file implements the SymbolTable class for the VMCore library.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/SymbolTable.h"
8 #include "llvm/InstrTypes.h"
9 #include "llvm/Support/StringExtras.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/Method.h"
12
13 #define DEBUG_SYMBOL_TABLE 0
14 #define DEBUG_ABSTYPE 0
15
16 SymbolTable::~SymbolTable() {
17   // Drop all abstract type references in the type plane...
18   iterator TyPlane = find(Type::TypeTy);
19   if (TyPlane != end()) {
20     VarMap &TyP = TyPlane->second;
21     for (VarMap::iterator I = TyP.begin(), E = TyP.end(); I != E; ++I) {
22       const Type *Ty = cast<const Type>(I->second);
23       if (Ty->isAbstract())   // If abstract, drop the reference...
24         cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
25     }
26   }
27 #ifndef NDEBUG   // Only do this in -g mode...
28   bool LeftoverValues = true;
29   for (iterator i = begin(); i != end(); ++i) {
30     for (type_iterator I = i->second.begin(); I != i->second.end(); ++I)
31       if (!isa<ConstPoolVal>(I->second) && !isa<Type>(I->second)) {
32         cerr << "Value still in symbol table! Type = '"
33              << i->first->getDescription() << "' Name = '" << I->first << "'\n";
34         LeftoverValues = false;
35       }
36   }
37   
38   assert(LeftoverValues && "Values remain in symbol table!");
39 #endif
40 }
41
42 // getUniqueName - Given a base name, return a string that is either equal to
43 // it (or derived from it) that does not already occur in the symbol table for
44 // the specified type.
45 //
46 string SymbolTable::getUniqueName(const Type *Ty, const string &BaseName) {
47   iterator I = find(Ty);
48   if (I == end()) return BaseName;
49
50   string TryName = BaseName;
51   unsigned Counter = 0;
52   type_iterator End = I->second.end();
53
54   while (I->second.find(TryName) != End)     // Loop until we find unoccupied
55     TryName = BaseName + utostr(++Counter);  // Name in the symbol table
56   return TryName;
57 }
58
59
60
61 // lookup - Returns null on failure...
62 Value *SymbolTable::lookup(const Type *Ty, const string &Name) {
63   iterator I = find(Ty);
64   if (I != end()) {                      // We have symbols in that plane...
65     type_iterator J = I->second.find(Name);
66     if (J != I->second.end())            // and the name is in our hash table...
67       return J->second;
68   }
69
70   return ParentSymTab ? ParentSymTab->lookup(Ty, Name) : 0;
71 }
72
73 void SymbolTable::remove(Value *N) {
74   assert(N->hasName() && "Value doesn't have name!");
75
76   iterator I = find(N->getType());
77   removeEntry(I, I->second.find(N->getName()));
78 }
79
80 // removeEntry - Remove a value from the symbol table...
81 //
82 Value *SymbolTable::removeEntry(iterator Plane, type_iterator Entry) {
83   if (InternallyInconsistent) return 0;
84   assert(Plane != super::end() &&
85          Entry != Plane->second.end() && "Invalid entry to remove!");
86
87   Value *Result = Entry->second;
88   const Type *Ty = Result->getType();
89 #if DEBUG_SYMBOL_TABLE
90   cerr << this << " Removing Value: " << Result->getName() << endl;
91 #endif
92
93   // Remove the value from the plane...
94   Plane->second.erase(Entry);
95
96   // If the plane is empty, remove it now!
97   if (Plane->second.empty()) {
98     // If the plane represented an abstract type that we were interested in,
99     // unlink ourselves from this plane.
100     //
101     if (Plane->first->isAbstract()) {
102 #if DEBUG_ABSTYPE
103       cerr << "Plane Empty: Removing type: " << Plane->first->getDescription()
104            << endl;
105 #endif
106       cast<DerivedType>(Plane->first)->removeAbstractTypeUser(this);
107     }
108
109     erase(Plane);
110   }
111
112   // If we are removing an abstract type, remove the symbol table from it's use
113   // list...
114   if (Ty == Type::TypeTy) {
115     const Type *T = cast<const Type>(Result);
116     if (T->isAbstract()) {
117 #if DEBUG_ABSTYPE
118       cerr << "Removing abs type from symtab" << T->getDescription() << endl;
119 #endif
120       cast<DerivedType>(T)->removeAbstractTypeUser(this);
121     }
122   }
123
124   return Result;
125 }
126
127 // insertEntry - Insert a value into the symbol table with the specified
128 // name...
129 //
130 void SymbolTable::insertEntry(const string &Name, const Type *VTy, Value *V) {
131   // TODO: The typeverifier should catch this when its implemented
132   assert(lookup(VTy, Name) == 0 && 
133          "SymbolTable::insertEntry - Name already in symbol table!");
134
135 #if DEBUG_SYMBOL_TABLE
136   cerr << this << " Inserting definition: " << Name << ": " 
137        << VTy->getDescription() << endl;
138 #endif
139
140   iterator I = find(VTy);
141   if (I == end()) {      // Not in collection yet... insert dummy entry
142     // Insert a new empty element.  I points to the new elements.
143     I = super::insert(make_pair(VTy, VarMap())).first;
144     assert(I != end() && "How did insert fail?");
145
146     // Check to see if the type is abstract.  If so, it might be refined in the
147     // future, which would cause the plane of the old type to get merged into
148     // a new type plane.
149     //
150     if (VTy->isAbstract()) {
151       cast<DerivedType>(VTy)->addAbstractTypeUser(this);
152 #if DEBUG_ABSTYPE
153       cerr << "Added abstract type value: " << VTy->getDescription() << endl;
154 #endif
155     }
156   }
157
158   I->second.insert(make_pair(Name, V));
159
160   // If we are adding an abstract type, add the symbol table to it's use list.
161   if (VTy == Type::TypeTy) {
162     const Type *T = cast<const Type>(V);
163     if (T->isAbstract()) {
164       cast<DerivedType>(T)->addAbstractTypeUser(this);
165 #if DEBUG_ABSTYPE
166       cerr << "Added abstract type to ST: " << T->getDescription() << endl;
167 #endif
168     }
169   }
170 }
171
172 // This function is called when one of the types in the type plane are refined
173 void SymbolTable::refineAbstractType(const DerivedType *OldType,
174                                      const Type *NewType) {
175   if (OldType == NewType) return;  // Noop, don't waste time dinking around
176
177   // Get a handle to the new type plane...
178   iterator NewTypeIt = find(NewType);
179   if (NewTypeIt == super::end()) {      // If no plane exists, add one
180     NewTypeIt = super::insert(make_pair(NewType, VarMap())).first;
181
182     if (NewType->isAbstract()) {
183       cast<DerivedType>(NewType)->addAbstractTypeUser(this);
184 #if DEBUG_ABSTYPE
185       cerr << "refined to abstype: " << NewType->getDescription() <<endl;
186 #endif
187     }
188   }
189
190   VarMap &NewPlane = NewTypeIt->second;
191
192   // Search to see if we have any values of the type oldtype.  If so, we need to
193   // move them into the newtype plane...
194   iterator TPI = find(OldType);
195   if (TPI != end()) {
196     VarMap &OldPlane = TPI->second;
197     while (!OldPlane.empty()) {
198       pair<const string, Value*> V = *OldPlane.begin();
199
200       // Check to see if there is already a value in the symbol table that this
201       // would collide with.
202       type_iterator TI = NewPlane.find(V.first);
203       if (TI != NewPlane.end() && TI->second == V.second) {
204         // No action
205
206       } else if (TI != NewPlane.end()) {
207         // The only thing we are allowing for now is two method prototypes being
208         // folded into one.
209         //
210         Method *ExistM = dyn_cast<Method>(TI->second);
211         Method *NewM = dyn_cast<Method>(V.second);
212
213         if (ExistM && NewM && ExistM->isExternal() && NewM->isExternal()) {
214           // Ok we have two external methods.  Make all uses of the new one
215           // use the old one...
216           //
217           NewM->replaceAllUsesWith(ExistM);
218           
219           // Now we just convert it to an unnamed method... which won't get
220           // added to our symbol table.  The problem is that if we call
221           // setName on the method that it will try to remove itself from
222           // the symbol table and die... because it's not in the symtab
223           // right now.  To fix this, we have an internally consistent flag
224           // that turns remove into a noop.  Thus the name will get null'd
225           // out, but the symbol table won't get upset.
226           //
227           InternallyInconsistent = true;
228
229           // Remove newM from the symtab
230           NewM->setName("");
231           InternallyInconsistent = false;
232         } else {
233           assert(0 && "Two ploanes folded together with overlapping "
234                  "value names!");
235         }
236       } else {
237         insertEntry(V.first, NewType, V.second);
238
239       }
240       // Remove the item from the old type plane
241       OldPlane.erase(OldPlane.begin());
242     }
243
244     // Ok, now we are not referencing the type anymore... take me off your user
245     // list please!
246 #if DEBUG_ABSTYPE
247     cerr << "Removing type " << OldType->getDescription() << endl;
248 #endif
249     OldType->removeAbstractTypeUser(this);
250
251     // Remove the plane that is no longer used
252     erase(TPI);
253   }
254
255   TPI = find(Type::TypeTy);
256   assert(TPI != end() &&"Type plane not in symbol table but we contain types!");
257
258   // Loop over all of the types in the symbol table, replacing any references to
259   // OldType with references to NewType.  Note that there may be multiple
260   // occurances, and although we only need to remove one at a time, it's faster
261   // to remove them all in one pass.
262   //
263   VarMap &TyPlane = TPI->second;
264   for (VarMap::iterator I = TyPlane.begin(), E = TyPlane.end(); I != E; ++I)
265     if (I->second == (Value*)OldType) {  // FIXME when Types aren't const.
266 #if DEBUG_ABSTYPE
267       cerr << "Removing type " << OldType->getDescription() << endl;
268 #endif
269       OldType->removeAbstractTypeUser(this);
270
271       I->second = (Value*)NewType;  // TODO FIXME when types aren't const
272       if (NewType->isAbstract()) {
273 #if DEBUG_ABSTYPE
274         cerr << "Added type " << NewType->getDescription() << endl;
275 #endif
276         cast<const DerivedType>(NewType)->addAbstractTypeUser(this);
277       }
278     }
279 }
280
281
282 #ifndef NDEBUG
283 #include "llvm/Assembly/Writer.h"
284 #include <algorithm>
285
286 static void DumpVal(const pair<const string, Value *> &V) {
287   cout << "  '" << V.first << "' = " << V.second << endl;
288 }
289
290 static void DumpPlane(const pair<const Type *, map<const string, Value *> >&P) {
291   cout << "  Plane: " << P.first << endl;
292   for_each(P.second.begin(), P.second.end(), DumpVal);
293 }
294
295 void SymbolTable::dump() const {
296   cout << "Symbol table dump:\n";
297   for_each(begin(), end(), DumpPlane);
298
299   if (ParentSymTab) {
300     cout << "Parent ";
301     ParentSymTab->dump();
302   }
303 }
304
305 #endif