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