Finegrainify namespacification
[oota-llvm.git] / lib / VMCore / Module.cpp
1 //===-- Module.cpp - Implement the Module class ---------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Module class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Module.h"
15 #include "llvm/InstrTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "Support/STLExtras.h"
19 #include "Support/LeakDetector.h"
20 #include "SymbolTableListTraitsImpl.h"
21 #include <algorithm>
22 #include <cstdarg>
23 #include <map>
24 using namespace llvm;
25
26 Function *ilist_traits<Function>::createNode() {
27   FunctionType *FTy =
28     FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
29   Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
30   // This should not be garbage monitored.
31   LeakDetector::removeGarbageObject(Ret);
32   return Ret;
33 }
34 GlobalVariable *ilist_traits<GlobalVariable>::createNode() {
35   GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
36                                            GlobalValue::ExternalLinkage);
37   // This should not be garbage monitored.
38   LeakDetector::removeGarbageObject(Ret);
39   return Ret;
40 }
41
42 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
43   return M->getFunctionList();
44 }
45 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
46   return M->getGlobalList();
47 }
48
49 // Explicit instantiations of SymbolTableListTraits since some of the methods
50 // are not in the public header file...
51 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
52 template class SymbolTableListTraits<Function, Module, Module>;
53
54 // Define the GlobalValueRefMap as a struct that wraps a map so that we don't
55 // have Module.h depend on <map>
56 //
57 namespace llvm {
58   struct GlobalValueRefMap {
59     typedef std::map<GlobalValue*, ConstantPointerRef*> MapTy;
60     typedef MapTy::iterator iterator;
61     std::map<GlobalValue*, ConstantPointerRef*> Map;
62   };
63 }
64
65
66 Module::Module(const std::string &MID)
67   : ModuleID(MID), Endian(AnyEndianness), PtrSize(AnyPointerSize) {
68   FunctionList.setItemParent(this);
69   FunctionList.setParent(this);
70   GlobalList.setItemParent(this);
71   GlobalList.setParent(this);
72   GVRefMap = 0;
73   SymTab = new SymbolTable();
74 }
75
76 Module::~Module() {
77   dropAllReferences();
78   GlobalList.clear();
79   GlobalList.setParent(0);
80   FunctionList.clear();
81   FunctionList.setParent(0);
82   delete SymTab;
83 }
84
85 // Module::dump() - Allow printing from debugger
86 void Module::dump() const {
87   print(std::cerr);
88 }
89
90 // getOrInsertFunction - Look up the specified function in the module symbol
91 // table.  If it does not exist, add a prototype for the function and return
92 // it.  This is nice because it allows most passes to get away with not handling
93 // the symbol table directly for this common task.
94 //
95 Function *Module::getOrInsertFunction(const std::string &Name,
96                                       const FunctionType *Ty) {
97   SymbolTable &SymTab = getSymbolTable();
98
99   // See if we have a definitions for the specified function already...
100   if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
101     return cast<Function>(V);      // Yup, got it
102   } else {                         // Nope, add one
103     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
104     FunctionList.push_back(New);
105     return New;                    // Return the new prototype...
106   }
107 }
108
109 // getOrInsertFunction - Look up the specified function in the module symbol
110 // table.  If it does not exist, add a prototype for the function and return it.
111 // This version of the method takes a null terminated list of function
112 // arguments, which makes it easier for clients to use.
113 //
114 Function *Module::getOrInsertFunction(const std::string &Name,
115                                       const Type *RetTy, ...) {
116   va_list Args;
117   va_start(Args, RetTy);
118
119   // Build the list of argument types...
120   std::vector<const Type*> ArgTys;
121   while (const Type *ArgTy = va_arg(Args, const Type*))
122     ArgTys.push_back(ArgTy);
123
124   va_end(Args);
125
126   // Build the function type and chain to the other getOrInsertFunction...
127   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
128 }
129
130
131
132 // getFunction - Look up the specified function in the module symbol table.
133 // If it does not exist, return null.
134 //
135 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
136   SymbolTable &SymTab = getSymbolTable();
137   return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
138 }
139
140 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
141 // there is already an entry for this name, true is returned and the symbol
142 // table is not modified.
143 //
144 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
145   SymbolTable &ST = getSymbolTable();
146
147   if (ST.lookup(Type::TypeTy, Name)) return true;  // Already in symtab...
148   
149   // Not in symbol table?  Set the name with the Symtab as an argument so the
150   // type knows what to update...
151   ((Value*)Ty)->setName(Name, &ST);
152
153   return false;
154 }
155
156 /// getMainFunction - This function looks up main efficiently.  This is such a
157 /// common case, that it is a method in Module.  If main cannot be found, a
158 /// null pointer is returned.
159 ///
160 Function *Module::getMainFunction() {
161   std::vector<const Type*> Params;
162
163   // int main(void)...
164   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
165                                                           Params, false)))
166     return F;
167
168   // void main(void)...
169   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
170                                                           Params, false)))
171     return F;
172
173   Params.push_back(Type::IntTy);
174
175   // int main(int argc)...
176   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
177                                                           Params, false)))
178     return F;
179
180   // void main(int argc)...
181   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
182                                                           Params, false)))
183     return F;
184
185   for (unsigned i = 0; i != 2; ++i) {  // Check argv and envp
186     Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
187
188     // int main(int argc, char **argv)...
189     if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
190                                                             Params, false)))
191       return F;
192     
193     // void main(int argc, char **argv)...
194     if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
195                                                             Params, false)))
196       return F;
197   }
198
199   // Ok, try to find main the hard way...
200   return getNamedFunction("main");
201 }
202
203 /// getNamedFunction - Return the first function in the module with the
204 /// specified name, of arbitrary type.  This method returns null if a function
205 /// with the specified name is not found.
206 ///
207 Function *Module::getNamedFunction(const std::string &Name) {
208   // Loop over all of the functions, looking for the function desired
209   Function *Found = 0;
210   for (iterator I = begin(), E = end(); I != E; ++I)
211     if (I->getName() == Name)
212       if (I->isExternal())
213         Found = I;
214       else
215         return I;
216   return Found; // Non-external function not found...
217 }
218
219
220
221 // getTypeName - If there is at least one entry in the symbol table for the
222 // specified type, return it.
223 //
224 std::string Module::getTypeName(const Type *Ty) {
225   const SymbolTable &ST = getSymbolTable();
226   if (ST.find(Type::TypeTy) == ST.end())
227     return ""; // No names for types...
228
229   SymbolTable::type_const_iterator TI = ST.type_begin(Type::TypeTy);
230   SymbolTable::type_const_iterator TE = ST.type_end(Type::TypeTy);
231
232   while (TI != TE && TI->second != (const Value*)Ty)
233     ++TI;
234
235   if (TI != TE)  // Must have found an entry!
236     return TI->first;
237   return "";     // Must not have found anything...
238 }
239
240
241 // dropAllReferences() - This function causes all the subelementss to "let go"
242 // of all references that they are maintaining.  This allows one to 'delete' a
243 // whole module at a time, even though there may be circular references... first
244 // all references are dropped, and all use counts go to zero.  Then everything
245 // is deleted for real.  Note that no operations are valid on an object that
246 // has "dropped all references", except operator delete.
247 //
248 void Module::dropAllReferences() {
249   for(Module::iterator I = begin(), E = end(); I != E; ++I)
250     I->dropAllReferences();
251
252   for(Module::giterator I = gbegin(), E = gend(); I != E; ++I)
253     I->dropAllReferences();
254
255   // If there are any GlobalVariable references still out there, nuke them now.
256   // Since all references are hereby dropped, nothing could possibly reference
257   // them still.  Note that destroying all of the constant pointer refs will
258   // eventually cause the GVRefMap field to be set to null (by
259   // destroyConstantPointerRef, below).
260   //
261   while (GVRefMap)
262     // Delete the ConstantPointerRef node...  
263     GVRefMap->Map.begin()->second->destroyConstant();
264 }
265
266 // Accessor for the underlying GlobalValRefMap...
267 ConstantPointerRef *Module::getConstantPointerRef(GlobalValue *V){
268   // Create ref map lazily on demand...
269   if (GVRefMap == 0) GVRefMap = new GlobalValueRefMap();
270
271   GlobalValueRefMap::iterator I = GVRefMap->Map.find(V);
272   if (I != GVRefMap->Map.end()) return I->second;
273
274   ConstantPointerRef *Ref = new ConstantPointerRef(V);
275   GVRefMap->Map[V] = Ref;
276   return Ref;
277 }
278
279 void Module::destroyConstantPointerRef(ConstantPointerRef *CPR) {
280   assert(GVRefMap && "No map allocated, but we have a CPR?");
281   if (!GVRefMap->Map.erase(CPR->getValue()))  // Remove it from the map...
282     assert(0 && "ConstantPointerRef not found in module CPR map!");
283   
284   if (GVRefMap->Map.empty()) {   // If the map is empty, delete it.
285     delete GVRefMap;
286     GVRefMap = 0;
287   }
288 }
289
290 void Module::mutateConstantPointerRef(GlobalValue *OldGV, GlobalValue *NewGV) {
291   assert(OldGV != NewGV && "Cannot mutate to the same global!");
292   GlobalValueRefMap::iterator I = GVRefMap->Map.find(OldGV);
293   assert(I != GVRefMap->Map.end() && 
294          "mutateConstantPointerRef; OldGV not in table!");
295   ConstantPointerRef *Ref = I->second;
296
297   // Remove the old entry...
298   GVRefMap->Map.erase(I);
299
300   // Check to see if a CPR already exists for NewGV
301   I = GVRefMap->Map.lower_bound(NewGV);
302
303   if (I == GVRefMap->Map.end() || I->first != NewGV) {
304     // Insert the new entry...
305     GVRefMap->Map.insert(I, std::make_pair(NewGV, Ref));
306   } else {
307     // Otherwise, an entry already exists for the current global value.
308     // Completely replace the old CPR with the existing one...
309     Ref->replaceAllUsesWith(I->second);
310     delete Ref;
311   }
312 }
313