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