For PR411:
[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 "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/LeakDetector.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include "llvm/TypeSymbolTable.h"
23 #include <algorithm>
24 #include <cstdarg>
25 #include <cstdlib>
26 #include <map>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // Methods to implement the globals and functions lists.
31 //
32
33 Function *ilist_traits<Function>::createSentinel() {
34   FunctionType *FTy =
35     FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false, 
36                       std::vector<FunctionType::ParameterAttributes>() );
37   Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
38   // This should not be garbage monitored.
39   LeakDetector::removeGarbageObject(Ret);
40   return Ret;
41 }
42 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
43   GlobalVariable *Ret = new GlobalVariable(Type::Int32Ty, false,
44                                            GlobalValue::ExternalLinkage);
45   // This should not be garbage monitored.
46   LeakDetector::removeGarbageObject(Ret);
47   return Ret;
48 }
49
50 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
51   return M->getFunctionList();
52 }
53 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
54   return M->getGlobalList();
55 }
56
57 // Explicit instantiations of SymbolTableListTraits since some of the methods
58 // are not in the public header file.
59 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
60 template class SymbolTableListTraits<Function, Module, Module>;
61
62 //===----------------------------------------------------------------------===//
63 // Primitive Module methods.
64 //
65
66 Module::Module(const std::string &MID)
67   : ModuleID(MID), DataLayout("") {
68   FunctionList.setItemParent(this);
69   FunctionList.setParent(this);
70   GlobalList.setItemParent(this);
71   GlobalList.setParent(this);
72   ValSymTab = new ValueSymbolTable();
73   TypeSymTab = new TypeSymbolTable();
74 }
75
76 Module::~Module() {
77   dropAllReferences();
78   GlobalList.clear();
79   GlobalList.setParent(0);
80   FunctionList.clear();
81   FunctionList.setParent(0);
82   LibraryList.clear();
83   delete ValSymTab;
84   delete TypeSymTab;
85 }
86
87 // Module::dump() - Allow printing from debugger
88 void Module::dump() const {
89   print(*cerr.stream());
90 }
91
92 /// Target endian information...
93 Module::Endianness Module::getEndianness() const {
94   std::string temp = DataLayout;
95   Module::Endianness ret = AnyEndianness;
96   
97   while (!temp.empty()) {
98     std::string token = getToken(temp, "-");
99     
100     if (token[0] == 'e') {
101       ret = LittleEndian;
102     } else if (token[0] == 'E') {
103       ret = BigEndian;
104     }
105   }
106   
107   return ret;
108 }
109
110 /// Target Pointer Size information...
111 Module::PointerSize Module::getPointerSize() const {
112   std::string temp = DataLayout;
113   Module::PointerSize ret = AnyPointerSize;
114   
115   while (!temp.empty()) {
116     std::string token = getToken(temp, "-");
117     char signal = getToken(token, ":")[0];
118     
119     if (signal == 'p') {
120       int size = atoi(getToken(token, ":").c_str());
121       if (size == 32)
122         ret = Pointer32;
123       else if (size == 64)
124         ret = Pointer64;
125     }
126   }
127   
128   return ret;
129 }
130
131 //===----------------------------------------------------------------------===//
132 // Methods for easy access to the functions in the module.
133 //
134
135 // getOrInsertFunction - Look up the specified function in the module symbol
136 // table.  If it does not exist, add a prototype for the function and return
137 // it.  This is nice because it allows most passes to get away with not handling
138 // the symbol table directly for this common task.
139 //
140 Constant *Module::getOrInsertFunction(const std::string &Name,
141                                       const FunctionType *Ty) {
142   ValueSymbolTable &SymTab = getValueSymbolTable();
143
144   // See if we have a definition for the specified function already.
145   GlobalValue *F = dyn_cast_or_null<GlobalValue>(SymTab.lookup(Name));
146   if (F == 0) {
147     // Nope, add it
148     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
149     FunctionList.push_back(New);
150     return New;                    // Return the new prototype.
151   }
152
153   // Okay, the function exists.  Does it have externally visible linkage?
154   if (F->hasInternalLinkage()) {
155     // Rename the function.
156     F->setName(SymTab.getUniqueName(F->getName()));
157     // Retry, now there won't be a conflict.
158     return getOrInsertFunction(Name, Ty);
159   }
160
161   // If the function exists but has the wrong type, return a bitcast to the
162   // right type.
163   if (F->getType() != PointerType::get(Ty))
164     return ConstantExpr::getBitCast(F, PointerType::get(Ty));
165   
166   // Otherwise, we just found the existing function or a prototype.
167   return F;  
168 }
169
170 // getOrInsertFunction - Look up the specified function in the module symbol
171 // table.  If it does not exist, add a prototype for the function and return it.
172 // This version of the method takes a null terminated list of function
173 // arguments, which makes it easier for clients to use.
174 //
175 Constant *Module::getOrInsertFunction(const std::string &Name,
176                                       const Type *RetTy, ...) {
177   va_list Args;
178   va_start(Args, RetTy);
179
180   // Build the list of argument types...
181   std::vector<const Type*> ArgTys;
182   while (const Type *ArgTy = va_arg(Args, const Type*))
183     ArgTys.push_back(ArgTy);
184
185   va_end(Args);
186
187   // Build the function type and chain to the other getOrInsertFunction...
188   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
189 }
190
191
192 // getFunction - Look up the specified function in the module symbol table.
193 // If it does not exist, return null.
194 //
195 Function *Module::getFunction(const std::string &Name) const {
196   const ValueSymbolTable &SymTab = getValueSymbolTable();
197   return dyn_cast_or_null<Function>(SymTab.lookup(Name));
198 }
199
200 //===----------------------------------------------------------------------===//
201 // Methods for easy access to the global variables in the module.
202 //
203
204 /// getGlobalVariable - Look up the specified global variable in the module
205 /// symbol table.  If it does not exist, return null.  The type argument
206 /// should be the underlying type of the global, i.e., it should not have
207 /// the top-level PointerType, which represents the address of the global.
208 /// If AllowInternal is set to true, this function will return types that
209 /// have InternalLinkage. By default, these types are not returned.
210 ///
211 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
212                                           bool AllowInternal) const {
213   if (Value *V = ValSymTab->lookup(Name)) {
214     GlobalVariable *Result = dyn_cast<GlobalVariable>(V);
215     if (Result && (AllowInternal || !Result->hasInternalLinkage()))
216       return Result;
217   }
218   return 0;
219 }
220
221 //===----------------------------------------------------------------------===//
222 // Methods for easy access to the types in the module.
223 //
224
225
226 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
227 // there is already an entry for this name, true is returned and the symbol
228 // table is not modified.
229 //
230 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
231   TypeSymbolTable &ST = getTypeSymbolTable();
232
233   if (ST.lookup(Name)) return true;  // Already in symtab...
234
235   // Not in symbol table?  Set the name with the Symtab as an argument so the
236   // type knows what to update...
237   ST.insert(Name, Ty);
238
239   return false;
240 }
241
242 /// getTypeByName - Return the type with the specified name in this module, or
243 /// null if there is none by that name.
244 const Type *Module::getTypeByName(const std::string &Name) const {
245   const TypeSymbolTable &ST = getTypeSymbolTable();
246   return cast_or_null<Type>(ST.lookup(Name));
247 }
248
249 // getTypeName - If there is at least one entry in the symbol table for the
250 // specified type, return it.
251 //
252 std::string Module::getTypeName(const Type *Ty) const {
253   const TypeSymbolTable &ST = getTypeSymbolTable();
254
255   TypeSymbolTable::const_iterator TI = ST.begin();
256   TypeSymbolTable::const_iterator TE = ST.end();
257   if ( TI == TE ) return ""; // No names for types
258
259   while (TI != TE && TI->second != Ty)
260     ++TI;
261
262   if (TI != TE)  // Must have found an entry!
263     return TI->first;
264   return "";     // Must not have found anything...
265 }
266
267 //===----------------------------------------------------------------------===//
268 // Other module related stuff.
269 //
270
271
272 // dropAllReferences() - This function causes all the subelementss to "let go"
273 // of all references that they are maintaining.  This allows one to 'delete' a
274 // whole module at a time, even though there may be circular references... first
275 // all references are dropped, and all use counts go to zero.  Then everything
276 // is deleted for real.  Note that no operations are valid on an object that
277 // has "dropped all references", except operator delete.
278 //
279 void Module::dropAllReferences() {
280   for(Module::iterator I = begin(), E = end(); I != E; ++I)
281     I->dropAllReferences();
282
283   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
284     I->dropAllReferences();
285 }
286
287 void Module::addLibrary(const std::string& Lib) {
288   for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
289     if (*I == Lib)
290       return;
291   LibraryList.push_back(Lib);
292 }
293
294 void Module::removeLibrary(const std::string& Lib) {
295   LibraryListType::iterator I = LibraryList.begin();
296   LibraryListType::iterator E = LibraryList.end();
297   for (;I != E; ++I)
298     if (*I == Lib) {
299       LibraryList.erase(I);
300       return;
301     }
302 }
303