1 //===-- Module.cpp - Implement the Module class ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Module class for the VMCore library.
12 //===----------------------------------------------------------------------===//
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"
29 //===----------------------------------------------------------------------===//
30 // Methods to implement the globals and functions lists.
33 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
34 GlobalVariable *Ret = new GlobalVariable(getGlobalContext(), Type::Int32Ty,
35 false, GlobalValue::ExternalLinkage);
36 // This should not be garbage monitored.
37 LeakDetector::removeGarbageObject(Ret);
40 GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
41 GlobalAlias *Ret = new GlobalAlias(Type::Int32Ty,
42 GlobalValue::ExternalLinkage);
43 // This should not be garbage monitored.
44 LeakDetector::removeGarbageObject(Ret);
48 // Explicit instantiations of SymbolTableListTraits since some of the methods
49 // are not in the public header file.
50 template class SymbolTableListTraits<GlobalVariable, Module>;
51 template class SymbolTableListTraits<Function, Module>;
52 template class SymbolTableListTraits<GlobalAlias, Module>;
54 //===----------------------------------------------------------------------===//
55 // Primitive Module methods.
58 Module::Module(const StringRef &MID, LLVMContext& C)
59 : Context(C), ModuleID(MID), DataLayout("") {
60 ValSymTab = new ValueSymbolTable();
61 TypeSymTab = new TypeSymbolTable();
74 /// Target endian information...
75 Module::Endianness Module::getEndianness() const {
76 std::string temp = DataLayout;
77 Module::Endianness ret = AnyEndianness;
79 while (!temp.empty()) {
80 std::string token = getToken(temp, "-");
82 if (token[0] == 'e') {
84 } else if (token[0] == 'E') {
92 /// Target Pointer Size information...
93 Module::PointerSize Module::getPointerSize() const {
94 std::string temp = DataLayout;
95 Module::PointerSize ret = AnyPointerSize;
97 while (!temp.empty()) {
98 std::string token = getToken(temp, "-");
99 char signal = getToken(token, ":")[0];
102 int size = atoi(getToken(token, ":").c_str());
113 /// getNamedValue - Return the first global value in the module with
114 /// the specified name, of arbitrary type. This method returns null
115 /// if a global with the specified name is not found.
116 GlobalValue *Module::getNamedValue(const StringRef &Name) const {
117 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
120 //===----------------------------------------------------------------------===//
121 // Methods for easy access to the functions in the module.
124 // getOrInsertFunction - Look up the specified function in the module symbol
125 // table. If it does not exist, add a prototype for the function and return
126 // it. This is nice because it allows most passes to get away with not handling
127 // the symbol table directly for this common task.
129 Constant *Module::getOrInsertFunction(const StringRef &Name,
130 const FunctionType *Ty,
131 AttrListPtr AttributeList) {
132 // See if we have a definition for the specified function already.
133 GlobalValue *F = getNamedValue(Name);
136 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
137 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
138 New->setAttributes(AttributeList);
139 FunctionList.push_back(New);
140 return New; // Return the new prototype.
143 // Okay, the function exists. Does it have externally visible linkage?
144 if (F->hasLocalLinkage()) {
145 // Clear the function's name.
147 // Retry, now there won't be a conflict.
148 Constant *NewF = getOrInsertFunction(Name, Ty);
153 // If the function exists but has the wrong type, return a bitcast to the
155 if (F->getType() != Context.getPointerTypeUnqual(Ty))
156 return Context.getConstantExprBitCast(F, Context.getPointerTypeUnqual(Ty));
158 // Otherwise, we just found the existing function or a prototype.
162 Constant *Module::getOrInsertTargetIntrinsic(const StringRef &Name,
163 const FunctionType *Ty,
164 AttrListPtr AttributeList) {
165 // See if we have a definition for the specified function already.
166 GlobalValue *F = getNamedValue(Name);
169 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
170 New->setAttributes(AttributeList);
171 FunctionList.push_back(New);
172 return New; // Return the new prototype.
175 // Otherwise, we just found the existing function or a prototype.
179 Constant *Module::getOrInsertFunction(const StringRef &Name,
180 const FunctionType *Ty) {
181 AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
182 return getOrInsertFunction(Name, Ty, AttributeList);
185 // getOrInsertFunction - Look up the specified function in the module symbol
186 // table. If it does not exist, add a prototype for the function and return it.
187 // This version of the method takes a null terminated list of function
188 // arguments, which makes it easier for clients to use.
190 Constant *Module::getOrInsertFunction(const StringRef &Name,
191 AttrListPtr AttributeList,
192 const Type *RetTy, ...) {
194 va_start(Args, RetTy);
196 // Build the list of argument types...
197 std::vector<const Type*> ArgTys;
198 while (const Type *ArgTy = va_arg(Args, const Type*))
199 ArgTys.push_back(ArgTy);
203 // Build the function type and chain to the other getOrInsertFunction...
204 return getOrInsertFunction(Name,
205 Context.getFunctionType(RetTy, ArgTys, false),
209 Constant *Module::getOrInsertFunction(const StringRef &Name,
210 const Type *RetTy, ...) {
212 va_start(Args, RetTy);
214 // Build the list of argument types...
215 std::vector<const Type*> ArgTys;
216 while (const Type *ArgTy = va_arg(Args, const Type*))
217 ArgTys.push_back(ArgTy);
221 // Build the function type and chain to the other getOrInsertFunction...
222 return getOrInsertFunction(Name,
223 Context.getFunctionType(RetTy, ArgTys, false),
224 AttrListPtr::get((AttributeWithIndex *)0, 0));
227 // getFunction - Look up the specified function in the module symbol table.
228 // If it does not exist, return null.
230 Function *Module::getFunction(const StringRef &Name) const {
231 return dyn_cast_or_null<Function>(getNamedValue(Name));
234 //===----------------------------------------------------------------------===//
235 // Methods for easy access to the global variables in the module.
238 /// getGlobalVariable - Look up the specified global variable in the module
239 /// symbol table. If it does not exist, return null. The type argument
240 /// should be the underlying type of the global, i.e., it should not have
241 /// the top-level PointerType, which represents the address of the global.
242 /// If AllowLocal is set to true, this function will return types that
243 /// have an local. By default, these types are not returned.
245 GlobalVariable *Module::getGlobalVariable(const StringRef &Name,
246 bool AllowLocal) const {
247 if (GlobalVariable *Result =
248 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
249 if (AllowLocal || !Result->hasLocalLinkage())
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
260 Constant *Module::getOrInsertGlobal(const StringRef &Name, const Type *Ty) {
261 // See if we have a definition for the specified global already.
262 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
265 GlobalVariable *New =
266 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
268 return New; // Return the new declaration.
271 // If the variable exists but has the wrong type, return a bitcast to the
273 if (GV->getType() != Context.getPointerTypeUnqual(Ty))
274 return Context.getConstantExprBitCast(GV, Context.getPointerTypeUnqual(Ty));
276 // Otherwise, we just found the existing function or a prototype.
280 //===----------------------------------------------------------------------===//
281 // Methods for easy access to the global variables in the module.
284 // getNamedAlias - Look up the specified global in the module symbol table.
285 // If it does not exist, return null.
287 GlobalAlias *Module::getNamedAlias(const StringRef &Name) const {
288 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
291 //===----------------------------------------------------------------------===//
292 // Methods for easy access to the types in the module.
296 // addTypeName - Insert an entry in the symbol table mapping Str to Type. If
297 // there is already an entry for this name, true is returned and the symbol
298 // table is not modified.
300 bool Module::addTypeName(const StringRef &Name, const Type *Ty) {
301 TypeSymbolTable &ST = getTypeSymbolTable();
303 if (ST.lookup(Name)) return true; // Already in symtab...
305 // Not in symbol table? Set the name with the Symtab as an argument so the
306 // type knows what to update...
312 /// getTypeByName - Return the type with the specified name in this module, or
313 /// null if there is none by that name.
314 const Type *Module::getTypeByName(const StringRef &Name) const {
315 const TypeSymbolTable &ST = getTypeSymbolTable();
316 return cast_or_null<Type>(ST.lookup(Name));
319 // getTypeName - If there is at least one entry in the symbol table for the
320 // specified type, return it.
322 std::string Module::getTypeName(const Type *Ty) const {
323 const TypeSymbolTable &ST = getTypeSymbolTable();
325 TypeSymbolTable::const_iterator TI = ST.begin();
326 TypeSymbolTable::const_iterator TE = ST.end();
327 if ( TI == TE ) return ""; // No names for types
329 while (TI != TE && TI->second != Ty)
332 if (TI != TE) // Must have found an entry!
334 return ""; // Must not have found anything...
337 //===----------------------------------------------------------------------===//
338 // Other module related stuff.
342 // dropAllReferences() - This function causes all the subelementss to "let go"
343 // of all references that they are maintaining. This allows one to 'delete' a
344 // whole module at a time, even though there may be circular references... first
345 // all references are dropped, and all use counts go to zero. Then everything
346 // is deleted for real. Note that no operations are valid on an object that
347 // has "dropped all references", except operator delete.
349 void Module::dropAllReferences() {
350 for(Module::iterator I = begin(), E = end(); I != E; ++I)
351 I->dropAllReferences();
353 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
354 I->dropAllReferences();
356 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
357 I->dropAllReferences();
360 void Module::addLibrary(const StringRef& Lib) {
361 for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
364 LibraryList.push_back(Lib);
367 void Module::removeLibrary(const StringRef& Lib) {
368 LibraryListType::iterator I = LibraryList.begin();
369 LibraryListType::iterator E = LibraryList.end();
372 LibraryList.erase(I);