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