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/GVMaterializer.h"
19
#include "llvm/LLVMContext.h"
20
#include "llvm/ADT/SmallString.h"
21
#include "llvm/ADT/STLExtras.h"
22
#include "llvm/ADT/StringExtras.h"
23
#include "llvm/Support/LeakDetector.h"
24
#include "SymbolTableListTraitsImpl.h"
25
#include "llvm/TypeSymbolTable.h"
31
//===----------------------------------------------------------------------===//
32
// Methods to implement the globals and functions lists.
35
GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
36
GlobalVariable *Ret = new GlobalVariable(Type::getInt32Ty(getGlobalContext()),
37
false, GlobalValue::ExternalLinkage);
38
// This should not be garbage monitored.
39
LeakDetector::removeGarbageObject(Ret);
42
GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
43
GlobalAlias *Ret = new GlobalAlias(Type::getInt32Ty(getGlobalContext()),
44
GlobalValue::ExternalLinkage);
45
// This should not be garbage monitored.
46
LeakDetector::removeGarbageObject(Ret);
50
// Explicit instantiations of SymbolTableListTraits since some of the methods
51
// are not in the public header file.
52
template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
53
template class llvm::SymbolTableListTraits<Function, Module>;
54
template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
56
//===----------------------------------------------------------------------===//
57
// Primitive Module methods.
60
Module::Module(StringRef MID, LLVMContext& C)
61
: Context(C), Materializer(NULL), ModuleID(MID) {
62
ValSymTab = new ValueSymbolTable();
63
TypeSymTab = new TypeSymbolTable();
64
NamedMDSymTab = new StringMap<NamedMDNode *>();
76
delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
79
/// Target endian information...
80
Module::Endianness Module::getEndianness() const {
81
StringRef temp = DataLayout;
82
Module::Endianness ret = AnyEndianness;
84
while (!temp.empty()) {
85
StringRef token = DataLayout;
86
tie(token, temp) = getToken(temp, "-");
88
if (token[0] == 'e') {
90
} else if (token[0] == 'E') {
98
/// Target Pointer Size information...
99
Module::PointerSize Module::getPointerSize() const {
100
StringRef temp = DataLayout;
101
Module::PointerSize ret = AnyPointerSize;
103
while (!temp.empty()) {
104
StringRef token, signalToken;
105
tie(token, temp) = getToken(temp, "-");
106
tie(signalToken, token) = getToken(token, ":");
108
if (signalToken[0] == 'p') {
110
getToken(token, ":").first.getAsInteger(10, size);
121
/// getNamedValue - Return the first global value in the module with
122
/// the specified name, of arbitrary type. This method returns null
123
/// if a global with the specified name is not found.
124
GlobalValue *Module::getNamedValue(StringRef Name) const {
125
return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
128
/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
129
/// This ID is uniqued across modules in the current LLVMContext.
130
unsigned Module::getMDKindID(StringRef Name) const {
131
return Context.getMDKindID(Name);
134
/// getMDKindNames - Populate client supplied SmallVector with the name for
135
/// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
136
/// so it is filled in as an empty string.
137
void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
138
return Context.getMDKindNames(Result);
142
//===----------------------------------------------------------------------===//
143
// Methods for easy access to the functions in the module.
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.
151
Constant *Module::getOrInsertFunction(StringRef 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);
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.
165
// Okay, the function exists. Does it have externally visible linkage?
166
if (F->hasLocalLinkage()) {
167
// Clear the function's name.
169
// Retry, now there won't be a conflict.
170
Constant *NewF = getOrInsertFunction(Name, Ty);
175
// If the function exists but has the wrong type, return a bitcast to the
177
if (F->getType() != PointerType::getUnqual(Ty))
178
return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
180
// Otherwise, we just found the existing function or a prototype.
184
Constant *Module::getOrInsertTargetIntrinsic(StringRef 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);
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.
197
// Otherwise, we just found the existing function or a prototype.
201
Constant *Module::getOrInsertFunction(StringRef Name,
202
const FunctionType *Ty) {
203
AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
204
return getOrInsertFunction(Name, Ty, AttributeList);
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.
212
Constant *Module::getOrInsertFunction(StringRef Name,
213
AttrListPtr AttributeList,
214
const Type *RetTy, ...) {
216
va_start(Args, RetTy);
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);
225
// Build the function type and chain to the other getOrInsertFunction...
226
return getOrInsertFunction(Name,
227
FunctionType::get(RetTy, ArgTys, false),
231
Constant *Module::getOrInsertFunction(StringRef Name,
232
const Type *RetTy, ...) {
234
va_start(Args, RetTy);
236
// Build the list of argument types...
237
std::vector<const Type*> ArgTys;
238
while (const Type *ArgTy = va_arg(Args, const Type*))
239
ArgTys.push_back(ArgTy);
243
// Build the function type and chain to the other getOrInsertFunction...
244
return getOrInsertFunction(Name,
245
FunctionType::get(RetTy, ArgTys, false),
246
AttrListPtr::get((AttributeWithIndex *)0, 0));
249
// getFunction - Look up the specified function in the module symbol table.
250
// If it does not exist, return null.
252
Function *Module::getFunction(StringRef Name) const {
253
return dyn_cast_or_null<Function>(getNamedValue(Name));
256
//===----------------------------------------------------------------------===//
257
// Methods for easy access to the global variables in the module.
260
/// getGlobalVariable - Look up the specified global variable in the module
261
/// symbol table. If it does not exist, return null. The type argument
262
/// should be the underlying type of the global, i.e., it should not have
263
/// the top-level PointerType, which represents the address of the global.
264
/// If AllowLocal is set to true, this function will return types that
265
/// have an local. By default, these types are not returned.
267
GlobalVariable *Module::getGlobalVariable(StringRef Name,
268
bool AllowLocal) const {
269
if (GlobalVariable *Result =
270
dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
271
if (AllowLocal || !Result->hasLocalLinkage())
276
/// getOrInsertGlobal - Look up the specified global in the module symbol table.
277
/// 1. If it does not exist, add a declaration of the global and return it.
278
/// 2. Else, the global exists but has the wrong type: return the function
279
/// with a constantexpr cast to the right type.
280
/// 3. Finally, if the existing global is the correct delclaration, return the
282
Constant *Module::getOrInsertGlobal(StringRef Name, const Type *Ty) {
283
// See if we have a definition for the specified global already.
284
GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
287
GlobalVariable *New =
288
new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
290
return New; // Return the new declaration.
293
// If the variable exists but has the wrong type, return a bitcast to the
295
if (GV->getType() != PointerType::getUnqual(Ty))
296
return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
298
// Otherwise, we just found the existing function or a prototype.
302
//===----------------------------------------------------------------------===//
303
// Methods for easy access to the global variables in the module.
306
// getNamedAlias - Look up the specified global in the module symbol table.
307
// If it does not exist, return null.
309
GlobalAlias *Module::getNamedAlias(StringRef Name) const {
310
return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
313
/// getNamedMetadata - Return the first NamedMDNode in the module with the
314
/// specified name. This method returns null if a NamedMDNode with the
315
/// specified name is not found.
316
NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
317
SmallString<256> NameData;
318
StringRef NameRef = Name.toStringRef(NameData);
319
return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
322
/// getOrInsertNamedMetadata - Return the first named MDNode in the module
323
/// with the specified name. This method returns a new NamedMDNode if a
324
/// NamedMDNode with the specified name is not found.
325
NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
327
(*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
329
NMD = new NamedMDNode(Name);
330
NMD->setParent(this);
331
NamedMDList.push_back(NMD);
336
void Module::eraseNamedMetadata(NamedMDNode *NMD) {
337
static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
338
NamedMDList.erase(NMD);
341
//===----------------------------------------------------------------------===//
342
// Methods for easy access to the types in the module.
346
// addTypeName - Insert an entry in the symbol table mapping Str to Type. If
347
// there is already an entry for this name, true is returned and the symbol
348
// table is not modified.
350
bool Module::addTypeName(StringRef Name, const Type *Ty) {
351
TypeSymbolTable &ST = getTypeSymbolTable();
353
if (ST.lookup(Name)) return true; // Already in symtab...
355
// Not in symbol table? Set the name with the Symtab as an argument so the
356
// type knows what to update...
362
/// getTypeByName - Return the type with the specified name in this module, or
363
/// null if there is none by that name.
364
const Type *Module::getTypeByName(StringRef Name) const {
365
const TypeSymbolTable &ST = getTypeSymbolTable();
366
return cast_or_null<Type>(ST.lookup(Name));
369
// getTypeName - If there is at least one entry in the symbol table for the
370
// specified type, return it.
372
std::string Module::getTypeName(const Type *Ty) const {
373
const TypeSymbolTable &ST = getTypeSymbolTable();
375
TypeSymbolTable::const_iterator TI = ST.begin();
376
TypeSymbolTable::const_iterator TE = ST.end();
377
if ( TI == TE ) return ""; // No names for types
379
while (TI != TE && TI->second != Ty)
382
if (TI != TE) // Must have found an entry!
384
return ""; // Must not have found anything...
387
//===----------------------------------------------------------------------===//
388
// Methods to control the materialization of GlobalValues in the Module.
390
void Module::setMaterializer(GVMaterializer *GVM) {
391
assert(!Materializer &&
392
"Module already has a GVMaterializer. Call MaterializeAllPermanently"
393
" to clear it out before setting another one.");
394
Materializer.reset(GVM);
397
bool Module::isMaterializable(const GlobalValue *GV) const {
399
return Materializer->isMaterializable(GV);
403
bool Module::isDematerializable(const GlobalValue *GV) const {
405
return Materializer->isDematerializable(GV);
409
bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
411
return Materializer->Materialize(GV, ErrInfo);
415
void Module::Dematerialize(GlobalValue *GV) {
417
return Materializer->Dematerialize(GV);
420
bool Module::MaterializeAll(std::string *ErrInfo) {
423
return Materializer->MaterializeModule(this, ErrInfo);
426
bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
427
if (MaterializeAll(ErrInfo))
429
Materializer.reset();
433
//===----------------------------------------------------------------------===//
434
// Other module related stuff.
438
// dropAllReferences() - This function causes all the subelementss to "let go"
439
// of all references that they are maintaining. This allows one to 'delete' a
440
// whole module at a time, even though there may be circular references... first
441
// all references are dropped, and all use counts go to zero. Then everything
442
// is deleted for real. Note that no operations are valid on an object that
443
// has "dropped all references", except operator delete.
445
void Module::dropAllReferences() {
446
for(Module::iterator I = begin(), E = end(); I != E; ++I)
447
I->dropAllReferences();
449
for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
450
I->dropAllReferences();
452
for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
453
I->dropAllReferences();
456
void Module::addLibrary(StringRef Lib) {
457
for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
460
LibraryList.push_back(Lib);
463
void Module::removeLibrary(StringRef Lib) {
464
LibraryListType::iterator I = LibraryList.begin();
465
LibraryListType::iterator E = LibraryList.end();
468
LibraryList.erase(I);