Remove some really gross and hard to understand code now that
[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
98   plane_iterator PI = pmap.find(N->getType());
99   assert(PI != pmap.end() &&
100          "Trying to remove a value that doesn't have a type plane yet!");
101   removeEntry(PI, PI->second.find(N->getName()));
102 }
103
104 /// changeName - Given a value with a non-empty name, remove its existing entry
105 /// from the symbol table and insert a new one for Name.  This is equivalent to
106 /// doing "remove(V), V->Name = Name, insert(V)", but is faster, and will not
107 /// temporarily remove the symbol table plane if V is the last value in the
108 /// symtab with that name (which could invalidate iterators to that plane).
109 void SymbolTable::changeName(Value *V, const std::string &name) {
110   assert(!V->getName().empty() && !name.empty() && V->getName() != name &&
111          "Illegal use of this method!");
112
113   plane_iterator PI = pmap.find(V->getType());
114   assert(PI != pmap.end() && "Value doesn't have an entry in this table?");
115   ValueMap &VM = PI->second;
116
117   value_iterator VI = VM.find(V->getName());
118   assert(VI != VM.end() && "Value does have an entry in this table?");
119
120   // Remove the old entry.
121   VM.erase(VI);
122
123   // See if we can insert the new name.
124   VI = VM.lower_bound(name);
125
126   // Is there a naming conflict?
127   if (VI != VM.end() && VI->first == name) {
128     V->Name = getUniqueName(V->getType(), name);
129     VM.insert(make_pair(V->Name, V));
130   } else {
131     V->Name = name;
132     VM.insert(VI, make_pair(name, V));
133   }
134 }
135
136
137 // removeEntry - Remove a value from the symbol table...
138 Value *SymbolTable::removeEntry(plane_iterator Plane, value_iterator Entry) {
139   assert(Plane != pmap.end() &&
140          Entry != Plane->second.end() && "Invalid entry to remove!");
141
142   Value *Result = Entry->second;
143 #if DEBUG_SYMBOL_TABLE
144   dump();
145   std::cerr << " Removing Value: " << Result->getName() << "\n";
146 #endif
147
148   // Remove the value from the plane...
149   Plane->second.erase(Entry);
150
151   // If the plane is empty, remove it now!
152   if (Plane->second.empty()) {
153     // If the plane represented an abstract type that we were interested in,
154     // unlink ourselves from this plane.
155     //
156     if (Plane->first->isAbstract()) {
157 #if DEBUG_ABSTYPE
158       std::cerr << "Plane Empty: Removing type: "
159                 << Plane->first->getDescription() << "\n";
160 #endif
161       cast<DerivedType>(Plane->first)->removeAbstractTypeUser(this);
162     }
163
164     pmap.erase(Plane);
165   }
166   return Result;
167 }
168
169
170 // remove - Remove a type
171 void SymbolTable::remove(const Type* Ty ) {
172   type_iterator TI = this->type_begin();
173   type_iterator TE = this->type_end();
174
175   // Search for the entry
176   while ( TI != TE && TI->second != Ty )
177     ++TI;
178
179   if ( TI != TE )
180     this->removeEntry( TI );
181 }
182
183
184 // removeEntry - Remove a type from the symbol table...
185 Type* SymbolTable::removeEntry(type_iterator Entry) {
186   assert( Entry != tmap.end() && "Invalid entry to remove!");
187
188   const Type* Result = Entry->second;
189
190 #if DEBUG_SYMBOL_TABLE
191   dump();
192   std::cerr << " Removing Value: " << Result->getName() << "\n";
193 #endif
194
195   tmap.erase(Entry);
196
197   // If we are removing an abstract type, remove the symbol table from it's use
198   // list...
199   if (Result->isAbstract()) {
200 #if DEBUG_ABSTYPE
201     std::cerr << "Removing abstract type from symtab" << Result->getDescription()<<"\n";
202 #endif
203     cast<DerivedType>(Result)->removeAbstractTypeUser(this);
204   }
205
206   return const_cast<Type*>(Result);
207 }
208
209
210 // insertEntry - Insert a value into the symbol table with the specified name.
211 void SymbolTable::insertEntry(const std::string &Name, const Type *VTy,
212                               Value *V) {
213   plane_iterator PI = pmap.find(VTy);   // Plane iterator
214   value_iterator VI;                    // Actual value iterator
215   ValueMap *VM;                         // The plane we care about.
216
217 #if DEBUG_SYMBOL_TABLE
218   dump();
219   std::cerr << " Inserting definition: " << Name << ": " 
220             << VTy->getDescription() << "\n";
221 #endif
222
223   if (PI == pmap.end()) {      // Not in collection yet... insert dummy entry
224     // Insert a new empty element.  I points to the new elements.
225     VM = &pmap.insert(make_pair(VTy, ValueMap())).first->second;
226     VI = VM->end();
227
228     // Check to see if the type is abstract.  If so, it might be refined in the
229     // future, which would cause the plane of the old type to get merged into
230     // a new type plane.
231     //
232     if (VTy->isAbstract()) {
233       cast<DerivedType>(VTy)->addAbstractTypeUser(this);
234 #if DEBUG_ABSTYPE
235       std::cerr << "Added abstract type value: " << VTy->getDescription()
236                 << "\n";
237 #endif
238     }
239
240   } else {
241     // Check to see if there is a naming conflict.  If so, rename this value!
242     VM = &PI->second;
243     VI = VM->lower_bound(Name);
244     if (VI != VM->end() && VI->first == Name) {
245       V->Name = getUniqueName(VTy, Name);
246       VM->insert(make_pair(V->Name, V));
247       return;
248     }
249   }
250
251   VM->insert(VI, make_pair(Name, V));
252 }
253
254
255 // insertEntry - Insert a value into the symbol table with the specified
256 // name...
257 //
258 void SymbolTable::insertEntry(const std::string& Name, const Type* T) {
259
260   // Check to see if there is a naming conflict.  If so, rename this type!
261   std::string UniqueName = Name;
262   if (lookupType(Name))
263     UniqueName = getUniqueName(T, Name);
264
265 #if DEBUG_SYMBOL_TABLE
266   dump();
267   std::cerr << " Inserting type: " << UniqueName << ": " 
268             << T->getDescription() << "\n";
269 #endif
270
271   // Insert the tmap entry
272   tmap.insert(make_pair(UniqueName, T));
273
274   // If we are adding an abstract type, add the symbol table to it's use list.
275   if (T->isAbstract()) {
276     cast<DerivedType>(T)->addAbstractTypeUser(this);
277 #if DEBUG_ABSTYPE
278     std::cerr << "Added abstract type to ST: " << T->getDescription() << "\n";
279 #endif
280   }
281 }
282
283 // Strip the symbol table of its names.
284 bool SymbolTable::strip() {
285   bool RemovedSymbol = false;
286   for (plane_iterator I = pmap.begin(); I != pmap.end();) {
287     // Removing items from the plane can cause the plane itself to get deleted.
288     // If this happens, make sure we incremented our plane iterator already!
289     ValueMap &Plane = (I++)->second;
290     value_iterator B = Plane.begin(), Bend = Plane.end();
291     while (B != Bend) {   // Found nonempty type plane!
292       Value *V = B->second;
293       if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()) {
294         // Set name to "", removing from symbol table!
295         V->setName("");
296         RemovedSymbol = true;
297       }
298       ++B;
299     }
300   }
301
302   for (type_iterator TI = tmap.begin(); TI != tmap.end(); ) {
303     const Type* T = (TI++)->second;
304     remove(T);
305     RemovedSymbol = true;
306   }
307  
308   return RemovedSymbol;
309 }
310
311
312 // This function is called when one of the types in the type plane are refined
313 void SymbolTable::refineAbstractType(const DerivedType *OldType,
314                                      const Type *NewType) {
315
316   // Search to see if we have any values of the type Oldtype.  If so, we need to
317   // move them into the newtype plane...
318   plane_iterator PI = pmap.find(OldType);
319   if (PI != pmap.end()) {
320     // Get a handle to the new type plane...
321     plane_iterator NewTypeIt = pmap.find(NewType);
322     if (NewTypeIt == pmap.end()) {      // If no plane exists, add one
323       NewTypeIt = pmap.insert(make_pair(NewType, ValueMap())).first;
324       
325       if (NewType->isAbstract()) {
326         cast<DerivedType>(NewType)->addAbstractTypeUser(this);
327 #if DEBUG_ABSTYPE
328         std::cerr << "[Added] refined to abstype: " << NewType->getDescription()
329                   << "\n";
330 #endif
331       }
332     }
333
334     ValueMap &NewPlane = NewTypeIt->second;
335     ValueMap &OldPlane = PI->second;
336     while (!OldPlane.empty()) {
337       std::pair<const std::string, Value*> V = *OldPlane.begin();
338
339       // Check to see if there is already a value in the symbol table that this
340       // would collide with.
341       value_iterator VI = NewPlane.find(V.first);
342       if (VI != NewPlane.end() && VI->second == V.second) {
343         // No action
344
345       } else if (VI != NewPlane.end()) {
346         // The only thing we are allowing for now is two external global values
347         // folded into one.
348         //
349         GlobalValue *ExistGV = dyn_cast<GlobalValue>(VI->second);
350         GlobalValue *NewGV = dyn_cast<GlobalValue>(V.second);
351
352         if (ExistGV && NewGV) {
353           assert((ExistGV->isExternal() || NewGV->isExternal()) &&
354                  "Two planes folded together with overlapping value names!");
355
356           // Make sure that ExistGV is the one we want to keep!
357           if (!NewGV->isExternal())
358             std::swap(NewGV, ExistGV);
359
360           // Ok we have two external global values.  Make all uses of the new
361           // one use the old one...
362           NewGV->uncheckedReplaceAllUsesWith(ExistGV);
363           
364           // Update NewGV's name, we're about the remove it from the symbol
365           // table.
366           NewGV->Name = "";
367
368           // Now we can remove this global from the module entirely...
369           Module *M = NewGV->getParent();
370           if (Function *F = dyn_cast<Function>(NewGV))
371             M->getFunctionList().remove(F);
372           else
373             M->getGlobalList().remove(cast<GlobalVariable>(NewGV));
374           delete NewGV;
375         } else {
376           // If they are not global values, they must be just random values who
377           // happen to conflict now that types have been resolved.  If this is
378           // the case, reinsert the value into the new plane, allowing it to get
379           // renamed.
380           assert(V.second->getType() == NewType &&"Type resolution is broken!");
381           insert(V.second);
382         }
383       } else {
384         insertEntry(V.first, NewType, V.second);
385       }
386       // Remove the item from the old type plane
387       OldPlane.erase(OldPlane.begin());
388     }
389
390     // Ok, now we are not referencing the type anymore... take me off your user
391     // list please!
392 #if DEBUG_ABSTYPE
393     std::cerr << "Removing type " << OldType->getDescription() << "\n";
394 #endif
395     OldType->removeAbstractTypeUser(this);
396
397     // Remove the plane that is no longer used
398     pmap.erase(PI);
399   }
400
401   // Loop over all of the types in the symbol table, replacing any references
402   // to OldType with references to NewType.  Note that there may be multiple
403   // occurrences, and although we only need to remove one at a time, it's
404   // faster to remove them all in one pass.
405   //
406   for (type_iterator I = type_begin(), E = type_end(); I != E; ++I) {
407     if (I->second == (Type*)OldType) {  // FIXME when Types aren't const.
408 #if DEBUG_ABSTYPE
409       std::cerr << "Removing type " << OldType->getDescription() << "\n";
410 #endif
411       OldType->removeAbstractTypeUser(this);
412         
413       I->second = (Type*)NewType;  // TODO FIXME when types aren't const
414       if (NewType->isAbstract()) {
415 #if DEBUG_ABSTYPE
416         std::cerr << "Added type " << NewType->getDescription() << "\n";
417 #endif
418         cast<DerivedType>(NewType)->addAbstractTypeUser(this);
419       }
420     }
421   }
422 }
423
424
425 // Handle situation where type becomes Concreate from Abstract
426 void SymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
427   plane_iterator PI = pmap.find(AbsTy);
428
429   // If there are any values in the symbol table of this type, then the type
430   // plane is a use of the abstract type which must be dropped.
431   if (PI != pmap.end())
432     AbsTy->removeAbstractTypeUser(this);
433
434   // Loop over all of the types in the symbol table, dropping any abstract
435   // type user entries for AbsTy which occur because there are names for the
436   // type.
437   for (type_iterator TI = type_begin(), TE = type_end(); TI != TE; ++TI)
438     if (TI->second == (Type*)AbsTy)   // FIXME when Types aren't const.
439       AbsTy->removeAbstractTypeUser(this);
440 }
441
442 static void DumpVal(const std::pair<const std::string, Value *> &V) {
443   std::cerr << "  '" << V.first << "' = ";
444   V.second->dump();
445   std::cerr << "\n";
446 }
447
448 static void DumpPlane(const std::pair<const Type *,
449                                       std::map<const std::string, Value *> >&P){
450   P.first->dump();
451   std::cerr << "\n";
452   for_each(P.second.begin(), P.second.end(), DumpVal);
453 }
454
455 static void DumpTypes(const std::pair<const std::string, const Type*>& T ) {
456   std::cerr << "  '" << T.first << "' = ";
457   T.second->dump();
458   std::cerr << "\n";
459 }
460
461 void SymbolTable::dump() const {
462   std::cerr << "Symbol table dump:\n  Plane:";
463   for_each(pmap.begin(), pmap.end(), DumpPlane);
464   std::cerr << "  Types: ";
465   for_each(tmap.begin(), tmap.end(), DumpTypes);
466 }
467
468 // vim: sw=2 ai