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