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