For PR411:
[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 "llvm/Support/Debug.h"
20 #include <algorithm>
21 using namespace llvm;
22
23 #define DEBUG_SYMBOL_TABLE 0
24 #define DEBUG_ABSTYPE 0
25
26 SymbolTable::~SymbolTable() {
27  // TODO: FIXME: BIG ONE: This doesn't unreference abstract types for the
28  // planes that could still have entries!
29
30 #ifndef NDEBUG   // Only do this in -g mode...
31   bool LeftoverValues = true;
32   for (plane_iterator PI = pmap.begin(); PI != pmap.end(); ++PI) {
33     for (value_iterator VI = PI->second.begin(); VI != PI->second.end(); ++VI)
34       if (!isa<Constant>(VI->second) ) {
35         DOUT << "Value still in symbol table! Type = '"
36              << PI->first->getDescription() << "' Name = '"
37              << VI->first << "'\n";
38         LeftoverValues = false;
39       }
40   }
41
42   assert(LeftoverValues && "Values remain in symbol table!");
43 #endif
44 }
45
46 // getUniqueName - Given a base name, return a string that is either equal to
47 // it (or derived from it) that does not already occur in the symbol table for
48 // the specified type.
49 //
50 std::string SymbolTable::getUniqueName(const Type *Ty,
51                                        const std::string &BaseName) const {
52   // Find the plane
53   plane_const_iterator PI = pmap.find(Ty);
54   if (PI == pmap.end()) return BaseName;
55
56   std::string TryName = BaseName;
57   const ValueMap& vmap = PI->second;
58   value_const_iterator End = vmap.end();
59
60   // See if the name exists
61   while (vmap.find(TryName) != End)            // Loop until we find a free
62     TryName = BaseName + utostr(++LastUnique); // name in the symbol table
63   return TryName;
64 }
65
66
67 // lookup a value - Returns null on failure...
68 Value *SymbolTable::lookup(const Type *Ty, const std::string &Name) const {
69   plane_const_iterator PI = pmap.find(Ty);
70   if (PI != pmap.end()) {                // We have symbols in that plane.
71     value_const_iterator VI = PI->second.find(Name);
72     if (VI != PI->second.end())          // and the name is in our hash table.
73       return VI->second;
74   }
75   return 0;
76 }
77
78
79 /// changeName - Given a value with a non-empty name, remove its existing entry
80 /// from the symbol table and insert a new one for Name.  This is equivalent to
81 /// doing "remove(V), V->Name = Name, insert(V)", but is faster, and will not
82 /// temporarily remove the symbol table plane if V is the last value in the
83 /// symtab with that name (which could invalidate iterators to that plane).
84 void SymbolTable::changeName(Value *V, const std::string &name) {
85   assert(!V->getName().empty() && !name.empty() && V->getName() != name &&
86          "Illegal use of this method!");
87
88   plane_iterator PI = pmap.find(V->getType());
89   assert(PI != pmap.end() && "Value doesn't have an entry in this table?");
90   ValueMap &VM = PI->second;
91
92   value_iterator VI = VM.find(V->getName());
93   assert(VI != VM.end() && "Value does have an entry in this table?");
94
95   // Remove the old entry.
96   VM.erase(VI);
97
98   // See if we can insert the new name.
99   VI = VM.lower_bound(name);
100
101   // Is there a naming conflict?
102   if (VI != VM.end() && VI->first == name) {
103     V->Name = getUniqueName(V->getType(), name);
104     VM.insert(make_pair(V->Name, V));
105   } else {
106     V->Name = name;
107     VM.insert(VI, make_pair(name, V));
108   }
109 }
110
111 // Remove a value
112 void SymbolTable::remove(Value *N) {
113   assert(N->hasName() && "Value doesn't have name!");
114
115   plane_iterator PI = pmap.find(N->getType());
116   assert(PI != pmap.end() &&
117          "Trying to remove a value that doesn't have a type plane yet!");
118   ValueMap &VM = PI->second;
119   value_iterator Entry = VM.find(N->getName());
120   assert(Entry != VM.end() && "Invalid entry to remove!");
121
122 #if DEBUG_SYMBOL_TABLE
123   dump();
124   DOUT << " Removing Value: " << Entry->second->getName() << "\n";
125 #endif
126
127   // Remove the value from the plane...
128   VM.erase(Entry);
129
130   // If the plane is empty, remove it now!
131   if (VM.empty()) {
132     // If the plane represented an abstract type that we were interested in,
133     // unlink ourselves from this plane.
134     //
135     if (N->getType()->isAbstract()) {
136 #if DEBUG_ABSTYPE
137       DOUT << "Plane Empty: Removing type: "
138            << N->getType()->getDescription() << "\n";
139 #endif
140       cast<DerivedType>(N->getType())->removeAbstractTypeUser(this);
141     }
142
143     pmap.erase(PI);
144   }
145 }
146
147
148 // insertEntry - Insert a value into the symbol table with the specified name.
149 void SymbolTable::insertEntry(const std::string &Name, const Type *VTy,
150                               Value *V) {
151   plane_iterator PI = pmap.find(VTy);   // Plane iterator
152   value_iterator VI;                    // Actual value iterator
153   ValueMap *VM;                         // The plane we care about.
154
155 #if DEBUG_SYMBOL_TABLE
156   dump();
157   DOUT << " Inserting definition: " << Name << ": "
158        << VTy->getDescription() << "\n";
159 #endif
160
161   if (PI == pmap.end()) {      // Not in collection yet... insert dummy entry
162     // Insert a new empty element.  I points to the new elements.
163     VM = &pmap.insert(make_pair(VTy, ValueMap())).first->second;
164     VI = VM->end();
165
166     // Check to see if the type is abstract.  If so, it might be refined in the
167     // future, which would cause the plane of the old type to get merged into
168     // a new type plane.
169     //
170     if (VTy->isAbstract()) {
171       cast<DerivedType>(VTy)->addAbstractTypeUser(this);
172 #if DEBUG_ABSTYPE
173       DOUT << "Added abstract type value: " << VTy->getDescription()
174            << "\n";
175 #endif
176     }
177
178   } else {
179     // Check to see if there is a naming conflict.  If so, rename this value!
180     VM = &PI->second;
181     VI = VM->lower_bound(Name);
182     if (VI != VM->end() && VI->first == Name) {
183       V->Name = getUniqueName(VTy, Name);
184       VM->insert(make_pair(V->Name, V));
185       return;
186     }
187   }
188
189   VM->insert(VI, make_pair(Name, V));
190 }
191
192
193
194 // Strip the symbol table of its names.
195 bool SymbolTable::strip() {
196   bool RemovedSymbol = false;
197   for (plane_iterator I = pmap.begin(); I != pmap.end();) {
198     // Removing items from the plane can cause the plane itself to get deleted.
199     // If this happens, make sure we incremented our plane iterator already!
200     ValueMap &Plane = (I++)->second;
201     value_iterator B = Plane.begin(), Bend = Plane.end();
202     while (B != Bend) {   // Found nonempty type plane!
203       Value *V = B->second;
204       ++B;
205       if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()) {
206         // Set name to "", removing from symbol table!
207         V->setName("");
208         RemovedSymbol = true;
209       }
210     }
211   }
212
213   return RemovedSymbol;
214 }
215
216
217 // This function is called when one of the types in the type plane are refined
218 void SymbolTable::refineAbstractType(const DerivedType *OldType,
219                                      const Type *NewType) {
220
221   // Search to see if we have any values of the type Oldtype.  If so, we need to
222   // move them into the newtype plane...
223   plane_iterator PI = pmap.find(OldType);
224   if (PI != pmap.end()) {
225     // Get a handle to the new type plane...
226     plane_iterator NewTypeIt = pmap.find(NewType);
227     if (NewTypeIt == pmap.end()) {      // If no plane exists, add one
228       NewTypeIt = pmap.insert(make_pair(NewType, ValueMap())).first;
229
230       if (NewType->isAbstract()) {
231         cast<DerivedType>(NewType)->addAbstractTypeUser(this);
232 #if DEBUG_ABSTYPE
233         DOUT << "[Added] refined to abstype: " << NewType->getDescription()
234              << "\n";
235 #endif
236       }
237     }
238
239     ValueMap &NewPlane = NewTypeIt->second;
240     ValueMap &OldPlane = PI->second;
241     while (!OldPlane.empty()) {
242       std::pair<const std::string, Value*> V = *OldPlane.begin();
243
244       // Check to see if there is already a value in the symbol table that this
245       // would collide with.
246       value_iterator VI = NewPlane.find(V.first);
247       if (VI != NewPlane.end() && VI->second == V.second) {
248         // No action
249
250       } else if (VI != NewPlane.end()) {
251         // The only thing we are allowing for now is two external global values
252         // folded into one.
253         //
254         GlobalValue *ExistGV = dyn_cast<GlobalValue>(VI->second);
255         GlobalValue *NewGV = dyn_cast<GlobalValue>(V.second);
256
257         if (ExistGV && NewGV) {
258           assert((ExistGV->isDeclaration() || NewGV->isDeclaration()) &&
259                  "Two planes folded together with overlapping value names!");
260
261           // Make sure that ExistGV is the one we want to keep!
262           if (!NewGV->isDeclaration())
263             std::swap(NewGV, ExistGV);
264
265           // Ok we have two external global values.  Make all uses of the new
266           // one use the old one...
267           NewGV->uncheckedReplaceAllUsesWith(ExistGV);
268
269           // Update NewGV's name, we're about the remove it from the symbol
270           // table.
271           NewGV->Name = "";
272
273           // Now we can remove this global from the module entirely...
274           Module *M = NewGV->getParent();
275           if (Function *F = dyn_cast<Function>(NewGV))
276             M->getFunctionList().remove(F);
277           else
278             M->getGlobalList().remove(cast<GlobalVariable>(NewGV));
279           delete NewGV;
280         } else {
281           // If they are not global values, they must be just random values who
282           // happen to conflict now that types have been resolved.  If this is
283           // the case, reinsert the value into the new plane, allowing it to get
284           // renamed.
285           assert(V.second->getType() == NewType &&"Type resolution is broken!");
286           insert(V.second);
287         }
288       } else {
289         insertEntry(V.first, NewType, V.second);
290       }
291       // Remove the item from the old type plane
292       OldPlane.erase(OldPlane.begin());
293     }
294
295     // Ok, now we are not referencing the type anymore... take me off your user
296     // list please!
297 #if DEBUG_ABSTYPE
298     DOUT << "Removing type " << OldType->getDescription() << "\n";
299 #endif
300     OldType->removeAbstractTypeUser(this);
301
302     // Remove the plane that is no longer used
303     pmap.erase(PI);
304   }
305 }
306
307
308 // Handle situation where type becomes Concreate from Abstract
309 void SymbolTable::typeBecameConcrete(const DerivedType *AbsTy) {
310   plane_iterator PI = pmap.find(AbsTy);
311
312   // If there are any values in the symbol table of this type, then the type
313   // plane is a use of the abstract type which must be dropped.
314   if (PI != pmap.end())
315     AbsTy->removeAbstractTypeUser(this);
316 }
317
318 static void DumpVal(const std::pair<const std::string, Value *> &V) {
319   DOUT << "  '" << V.first << "' = ";
320   V.second->dump();
321   DOUT << "\n";
322 }
323
324 static void DumpPlane(const std::pair<const Type *,
325                                       std::map<const std::string, Value *> >&P){
326   P.first->dump();
327   DOUT << "\n";
328   for_each(P.second.begin(), P.second.end(), DumpVal);
329 }
330
331 void SymbolTable::dump() const {
332   DOUT << "Symbol table dump:\n  Plane:";
333   for_each(pmap.begin(), pmap.end(), DumpPlane);
334 }
335
336 // vim: sw=2 ai