Add Module::getNamedValue; use to normalize access to Module symbol
[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 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 // Methods to implement the globals and functions lists.
30 //
31
32 Function *ilist_traits<Function>::createSentinel() {
33   FunctionType *FTy =
34     FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
35   Function *Ret = Function::Create(FTy, GlobalValue::ExternalLinkage);
36   // This should not be garbage monitored.
37   LeakDetector::removeGarbageObject(Ret);
38   return Ret;
39 }
40 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
41   GlobalVariable *Ret = new GlobalVariable(Type::Int32Ty, false,
42                                            GlobalValue::ExternalLinkage);
43   // This should not be garbage monitored.
44   LeakDetector::removeGarbageObject(Ret);
45   return Ret;
46 }
47 GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
48   GlobalAlias *Ret = new GlobalAlias(Type::Int32Ty,
49                                      GlobalValue::ExternalLinkage);
50   // This should not be garbage monitored.
51   LeakDetector::removeGarbageObject(Ret);
52   return Ret;
53 }
54
55 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
56   return M->getFunctionList();
57 }
58 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
59   return M->getGlobalList();
60 }
61 iplist<GlobalAlias> &ilist_traits<GlobalAlias>::getList(Module *M) {
62   return M->getAliasList();
63 }
64
65 // Explicit instantiations of SymbolTableListTraits since some of the methods
66 // are not in the public header file.
67 template class SymbolTableListTraits<GlobalVariable, Module>;
68 template class SymbolTableListTraits<Function, Module>;
69 template class SymbolTableListTraits<GlobalAlias, Module>;
70
71 //===----------------------------------------------------------------------===//
72 // Primitive Module methods.
73 //
74
75 Module::Module(const std::string &MID)
76   : ModuleID(MID), DataLayout("") {
77   ValSymTab = new ValueSymbolTable();
78   TypeSymTab = new TypeSymbolTable();
79 }
80
81 Module::~Module() {
82   dropAllReferences();
83   GlobalList.clear();
84   FunctionList.clear();
85   AliasList.clear();
86   LibraryList.clear();
87   delete ValSymTab;
88   delete TypeSymTab;
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 /// getNamedValue - Return the first global value in the module with
131 /// the specified name, of arbitrary type.  This method returns null
132 /// if a global with the specified name is not found.
133 GlobalValue *Module::getNamedValue(const std::string &Name) const {
134   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
135 }
136
137 GlobalValue *Module::getNamedValue(const char *Name) const {
138   llvm::Value *V = getValueSymbolTable().lookup(Name, Name+strlen(Name));
139   return cast_or_null<GlobalValue>(V);
140 }
141
142 //===----------------------------------------------------------------------===//
143 // Methods for easy access to the functions in the module.
144 //
145
146 // getOrInsertFunction - Look up the specified function in the module symbol
147 // table.  If it does not exist, add a prototype for the function and return
148 // it.  This is nice because it allows most passes to get away with not handling
149 // the symbol table directly for this common task.
150 //
151 Constant *Module::getOrInsertFunction(const std::string &Name,
152                                       const FunctionType *Ty,
153                                       AttrListPtr AttributeList) {
154   // See if we have a definition for the specified function already.
155   GlobalValue *F = getNamedValue(Name);
156   if (F == 0) {
157     // Nope, add it
158     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
159     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
160       New->setAttributes(AttributeList);
161     FunctionList.push_back(New);
162     return New;                    // Return the new prototype.
163   }
164
165   // Okay, the function exists.  Does it have externally visible linkage?
166   if (F->hasLocalLinkage()) {
167     // Clear the function's name.
168     F->setName("");
169     // Retry, now there won't be a conflict.
170     Constant *NewF = getOrInsertFunction(Name, Ty);
171     F->setName(&Name[0], Name.size());
172     return NewF;
173   }
174
175   // If the function exists but has the wrong type, return a bitcast to the
176   // right type.
177   if (F->getType() != PointerType::getUnqual(Ty))
178     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
179   
180   // Otherwise, we just found the existing function or a prototype.
181   return F;  
182 }
183
184 Constant *Module::getOrInsertTargetIntrinsic(const std::string &Name,
185                                              const FunctionType *Ty,
186                                              AttrListPtr AttributeList) {
187   // See if we have a definition for the specified function already.
188   GlobalValue *F = getNamedValue(Name);
189   if (F == 0) {
190     // Nope, add it
191     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
192     New->setAttributes(AttributeList);
193     FunctionList.push_back(New);
194     return New; // Return the new prototype.
195   }
196
197   // Otherwise, we just found the existing function or a prototype.
198   return F;  
199 }
200
201 Constant *Module::getOrInsertFunction(const std::string &Name,
202                                       const FunctionType *Ty) {
203   AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
204   return getOrInsertFunction(Name, Ty, AttributeList);
205 }
206
207 // getOrInsertFunction - Look up the specified function in the module symbol
208 // table.  If it does not exist, add a prototype for the function and return it.
209 // This version of the method takes a null terminated list of function
210 // arguments, which makes it easier for clients to use.
211 //
212 Constant *Module::getOrInsertFunction(const std::string &Name,
213                                       AttrListPtr AttributeList,
214                                       const Type *RetTy, ...) {
215   va_list Args;
216   va_start(Args, RetTy);
217
218   // Build the list of argument types...
219   std::vector<const Type*> ArgTys;
220   while (const Type *ArgTy = va_arg(Args, const Type*))
221     ArgTys.push_back(ArgTy);
222
223   va_end(Args);
224
225   // Build the function type and chain to the other getOrInsertFunction...
226   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false),
227                              AttributeList);
228 }
229
230 Constant *Module::getOrInsertFunction(const std::string &Name,
231                                       const Type *RetTy, ...) {
232   va_list Args;
233   va_start(Args, RetTy);
234
235   // Build the list of argument types...
236   std::vector<const Type*> ArgTys;
237   while (const Type *ArgTy = va_arg(Args, const Type*))
238     ArgTys.push_back(ArgTy);
239
240   va_end(Args);
241
242   // Build the function type and chain to the other getOrInsertFunction...
243   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false),
244                              AttrListPtr::get((AttributeWithIndex *)0, 0));
245 }
246
247 // getFunction - Look up the specified function in the module symbol table.
248 // If it does not exist, return null.
249 //
250 Function *Module::getFunction(const std::string &Name) const {
251   return dyn_cast_or_null<Function>(getNamedValue(Name));
252 }
253
254 Function *Module::getFunction(const char *Name) const {
255   return dyn_cast_or_null<Function>(getNamedValue(Name));
256 }
257
258 //===----------------------------------------------------------------------===//
259 // Methods for easy access to the global variables in the module.
260 //
261
262 /// getGlobalVariable - Look up the specified global variable in the module
263 /// symbol table.  If it does not exist, return null.  The type argument
264 /// should be the underlying type of the global, i.e., it should not have
265 /// the top-level PointerType, which represents the address of the global.
266 /// If AllowLocal is set to true, this function will return types that
267 /// have an local. By default, these types are not returned.
268 ///
269 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
270                                           bool AllowLocal) const {
271   if (GlobalVariable *Result = 
272       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
273     if (AllowLocal || !Result->hasLocalLinkage())
274       return Result;
275   return 0;
276 }
277
278 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
279 ///   1. If it does not exist, add a declaration of the global and return it.
280 ///   2. Else, the global exists but has the wrong type: return the function
281 ///      with a constantexpr cast to the right type.
282 ///   3. Finally, if the existing global is the correct delclaration, return the
283 ///      existing global.
284 Constant *Module::getOrInsertGlobal(const std::string &Name, const Type *Ty) {
285   // See if we have a definition for the specified global already.
286   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
287   if (GV == 0) {
288     // Nope, add it
289     GlobalVariable *New =
290       new GlobalVariable(Ty, false, GlobalVariable::ExternalLinkage, 0, Name);
291     GlobalList.push_back(New);
292     return New;                    // Return the new declaration.
293   }
294
295   // If the variable exists but has the wrong type, return a bitcast to the
296   // right type.
297   if (GV->getType() != PointerType::getUnqual(Ty))
298     return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
299   
300   // Otherwise, we just found the existing function or a prototype.
301   return GV;
302 }
303
304 //===----------------------------------------------------------------------===//
305 // Methods for easy access to the global variables in the module.
306 //
307
308 // getNamedAlias - Look up the specified global in the module symbol table.
309 // If it does not exist, return null.
310 //
311 GlobalAlias *Module::getNamedAlias(const std::string &Name) const {
312   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
313 }
314
315 //===----------------------------------------------------------------------===//
316 // Methods for easy access to the types in the module.
317 //
318
319
320 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
321 // there is already an entry for this name, true is returned and the symbol
322 // table is not modified.
323 //
324 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
325   TypeSymbolTable &ST = getTypeSymbolTable();
326
327   if (ST.lookup(Name)) return true;  // Already in symtab...
328
329   // Not in symbol table?  Set the name with the Symtab as an argument so the
330   // type knows what to update...
331   ST.insert(Name, Ty);
332
333   return false;
334 }
335
336 /// getTypeByName - Return the type with the specified name in this module, or
337 /// null if there is none by that name.
338 const Type *Module::getTypeByName(const std::string &Name) const {
339   const TypeSymbolTable &ST = getTypeSymbolTable();
340   return cast_or_null<Type>(ST.lookup(Name));
341 }
342
343 // getTypeName - If there is at least one entry in the symbol table for the
344 // specified type, return it.
345 //
346 std::string Module::getTypeName(const Type *Ty) const {
347   const TypeSymbolTable &ST = getTypeSymbolTable();
348
349   TypeSymbolTable::const_iterator TI = ST.begin();
350   TypeSymbolTable::const_iterator TE = ST.end();
351   if ( TI == TE ) return ""; // No names for types
352
353   while (TI != TE && TI->second != Ty)
354     ++TI;
355
356   if (TI != TE)  // Must have found an entry!
357     return TI->first;
358   return "";     // Must not have found anything...
359 }
360
361 //===----------------------------------------------------------------------===//
362 // Other module related stuff.
363 //
364
365
366 // dropAllReferences() - This function causes all the subelementss to "let go"
367 // of all references that they are maintaining.  This allows one to 'delete' a
368 // whole module at a time, even though there may be circular references... first
369 // all references are dropped, and all use counts go to zero.  Then everything
370 // is deleted for real.  Note that no operations are valid on an object that
371 // has "dropped all references", except operator delete.
372 //
373 void Module::dropAllReferences() {
374   for(Module::iterator I = begin(), E = end(); I != E; ++I)
375     I->dropAllReferences();
376
377   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
378     I->dropAllReferences();
379
380   for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
381     I->dropAllReferences();
382 }
383
384 void Module::addLibrary(const std::string& Lib) {
385   for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
386     if (*I == Lib)
387       return;
388   LibraryList.push_back(Lib);
389 }
390
391 void Module::removeLibrary(const std::string& Lib) {
392   LibraryListType::iterator I = LibraryList.begin();
393   LibraryListType::iterator E = LibraryList.end();
394   for (;I != E; ++I)
395     if (*I == Lib) {
396       LibraryList.erase(I);
397       return;
398     }
399 }