Add the private linkage.
[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 //===----------------------------------------------------------------------===//
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                                       AttrListPtr AttributeList) {
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 = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
149     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
150       New->setAttributes(AttributeList);
151     FunctionList.push_back(New);
152     return New;                    // Return the new prototype.
153   }
154
155   // Okay, the function exists.  Does it have externally visible linkage?
156   if (F->hasLocalLinkage()) {
157     // Clear the function's name.
158     F->setName("");
159     // Retry, now there won't be a conflict.
160     Constant *NewF = getOrInsertFunction(Name, Ty);
161     F->setName(&Name[0], Name.size());
162     return NewF;
163   }
164
165   // If the function exists but has the wrong type, return a bitcast to the
166   // right type.
167   if (F->getType() != PointerType::getUnqual(Ty))
168     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
169   
170   // Otherwise, we just found the existing function or a prototype.
171   return F;  
172 }
173
174 Constant *Module::getOrInsertFunction(const std::string &Name,
175                                       const FunctionType *Ty) {
176   AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
177   return getOrInsertFunction(Name, Ty, AttributeList);
178 }
179
180 // getOrInsertFunction - Look up the specified function in the module symbol
181 // table.  If it does not exist, add a prototype for the function and return it.
182 // This version of the method takes a null terminated list of function
183 // arguments, which makes it easier for clients to use.
184 //
185 Constant *Module::getOrInsertFunction(const std::string &Name,
186                                       AttrListPtr AttributeList,
187                                       const Type *RetTy, ...) {
188   va_list Args;
189   va_start(Args, RetTy);
190
191   // Build the list of argument types...
192   std::vector<const Type*> ArgTys;
193   while (const Type *ArgTy = va_arg(Args, const Type*))
194     ArgTys.push_back(ArgTy);
195
196   va_end(Args);
197
198   // Build the function type and chain to the other getOrInsertFunction...
199   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false),
200                              AttributeList);
201 }
202
203 Constant *Module::getOrInsertFunction(const std::string &Name,
204                                       const Type *RetTy, ...) {
205   va_list Args;
206   va_start(Args, RetTy);
207
208   // Build the list of argument types...
209   std::vector<const Type*> ArgTys;
210   while (const Type *ArgTy = va_arg(Args, const Type*))
211     ArgTys.push_back(ArgTy);
212
213   va_end(Args);
214
215   // Build the function type and chain to the other getOrInsertFunction...
216   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false),
217                              AttrListPtr::get((AttributeWithIndex *)0, 0));
218 }
219
220 // getFunction - Look up the specified function in the module symbol table.
221 // If it does not exist, return null.
222 //
223 Function *Module::getFunction(const std::string &Name) const {
224   const ValueSymbolTable &SymTab = getValueSymbolTable();
225   return dyn_cast_or_null<Function>(SymTab.lookup(Name));
226 }
227
228 Function *Module::getFunction(const char *Name) const {
229   const ValueSymbolTable &SymTab = getValueSymbolTable();
230   return dyn_cast_or_null<Function>(SymTab.lookup(Name, Name+strlen(Name)));
231 }
232
233 //===----------------------------------------------------------------------===//
234 // Methods for easy access to the global variables in the module.
235 //
236
237 /// getGlobalVariable - Look up the specified global variable in the module
238 /// symbol table.  If it does not exist, return null.  The type argument
239 /// should be the underlying type of the global, i.e., it should not have
240 /// the top-level PointerType, which represents the address of the global.
241 /// If AllowLocal is set to true, this function will return types that
242 /// have an local. By default, these types are not returned.
243 ///
244 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
245                                           bool AllowLocal) const {
246   if (Value *V = ValSymTab->lookup(Name)) {
247     GlobalVariable *Result = dyn_cast<GlobalVariable>(V);
248     if (Result && (AllowLocal || !Result->hasLocalLinkage()))
249       return Result;
250   }
251   return 0;
252 }
253
254 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
255 ///   1. If it does not exist, add a declaration of the global and return it.
256 ///   2. Else, the global exists but has the wrong type: return the function
257 ///      with a constantexpr cast to the right type.
258 ///   3. Finally, if the existing global is the correct delclaration, return the
259 ///      existing global.
260 Constant *Module::getOrInsertGlobal(const std::string &Name, const Type *Ty) {
261   ValueSymbolTable &SymTab = getValueSymbolTable();
262
263   // See if we have a definition for the specified global already.
264   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(SymTab.lookup(Name));
265   if (GV == 0) {
266     // Nope, add it
267     GlobalVariable *New =
268       new GlobalVariable(Ty, false, GlobalVariable::ExternalLinkage, 0, Name);
269     GlobalList.push_back(New);
270     return New;                    // Return the new declaration.
271   }
272
273   // If the variable exists but has the wrong type, return a bitcast to the
274   // right type.
275   if (GV->getType() != PointerType::getUnqual(Ty))
276     return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
277   
278   // Otherwise, we just found the existing function or a prototype.
279   return GV;
280 }
281
282 //===----------------------------------------------------------------------===//
283 // Methods for easy access to the global variables in the module.
284 //
285
286 // getNamedAlias - Look up the specified global in the module symbol table.
287 // If it does not exist, return null.
288 //
289 GlobalAlias *Module::getNamedAlias(const std::string &Name) const {
290   const ValueSymbolTable &SymTab = getValueSymbolTable();
291   return dyn_cast_or_null<GlobalAlias>(SymTab.lookup(Name));
292 }
293
294 //===----------------------------------------------------------------------===//
295 // Methods for easy access to the types in the module.
296 //
297
298
299 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
300 // there is already an entry for this name, true is returned and the symbol
301 // table is not modified.
302 //
303 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
304   TypeSymbolTable &ST = getTypeSymbolTable();
305
306   if (ST.lookup(Name)) return true;  // Already in symtab...
307
308   // Not in symbol table?  Set the name with the Symtab as an argument so the
309   // type knows what to update...
310   ST.insert(Name, Ty);
311
312   return false;
313 }
314
315 /// getTypeByName - Return the type with the specified name in this module, or
316 /// null if there is none by that name.
317 const Type *Module::getTypeByName(const std::string &Name) const {
318   const TypeSymbolTable &ST = getTypeSymbolTable();
319   return cast_or_null<Type>(ST.lookup(Name));
320 }
321
322 // getTypeName - If there is at least one entry in the symbol table for the
323 // specified type, return it.
324 //
325 std::string Module::getTypeName(const Type *Ty) const {
326   const TypeSymbolTable &ST = getTypeSymbolTable();
327
328   TypeSymbolTable::const_iterator TI = ST.begin();
329   TypeSymbolTable::const_iterator TE = ST.end();
330   if ( TI == TE ) return ""; // No names for types
331
332   while (TI != TE && TI->second != Ty)
333     ++TI;
334
335   if (TI != TE)  // Must have found an entry!
336     return TI->first;
337   return "";     // Must not have found anything...
338 }
339
340 //===----------------------------------------------------------------------===//
341 // Other module related stuff.
342 //
343
344
345 // dropAllReferences() - This function causes all the subelementss to "let go"
346 // of all references that they are maintaining.  This allows one to 'delete' a
347 // whole module at a time, even though there may be circular references... first
348 // all references are dropped, and all use counts go to zero.  Then everything
349 // is deleted for real.  Note that no operations are valid on an object that
350 // has "dropped all references", except operator delete.
351 //
352 void Module::dropAllReferences() {
353   for(Module::iterator I = begin(), E = end(); I != E; ++I)
354     I->dropAllReferences();
355
356   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
357     I->dropAllReferences();
358
359   for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
360     I->dropAllReferences();
361 }
362
363 void Module::addLibrary(const std::string& Lib) {
364   for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
365     if (*I == Lib)
366       return;
367   LibraryList.push_back(Lib);
368 }
369
370 void Module::removeLibrary(const std::string& Lib) {
371   LibraryListType::iterator I = LibraryList.begin();
372   LibraryListType::iterator E = LibraryList.end();
373   for (;I != E; ++I)
374     if (*I == Lib) {
375       LibraryList.erase(I);
376       return;
377     }
378 }