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