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