Files

542 lines
19 KiB
C++
Raw Permalink Normal View History

2003-10-13 03:32:08 +00:00
//===-- Module.cpp - Implement the Module class ---------------------------===//
2005-04-21 23:48:37 +00:00
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
2005-04-21 23:48:37 +00:00
//
//===----------------------------------------------------------------------===//
2001-06-06 20:29:01 +00:00
//
2013-01-02 09:10:48 +00:00
// This file implements the Module class for the IR library.
2001-06-06 20:29:01 +00:00
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Module.h"
#include "SymbolTableListTraitsImpl.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/GVMaterializer.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/TypeFinder.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/MemoryBuffer.h"
2014-06-25 15:21:42 +00:00
#include "llvm/Support/Path.h"
#include "llvm/Support/RandomNumberGenerator.h"
2002-06-25 16:13:24 +00:00
#include <algorithm>
2003-08-31 00:19:28 +00:00
#include <cstdarg>
#include <cstdlib>
2003-11-21 20:23:48 +00:00
using namespace llvm;
//===----------------------------------------------------------------------===//
2004-04-21 18:27:56 +00:00
// Methods to implement the globals and functions lists.
//
2002-06-25 16:13:24 +00:00
// Explicit instantiations of SymbolTableListTraits since some of the methods
2006-01-24 04:13:11 +00:00
// are not in the public header file.
template class llvm::SymbolTableListTraits<Function>;
template class llvm::SymbolTableListTraits<GlobalVariable>;
template class llvm::SymbolTableListTraits<GlobalAlias>;
2016-04-07 12:32:19 +00:00
template class llvm::SymbolTableListTraits<GlobalIFunc>;
2001-06-06 20:29:01 +00:00
//===----------------------------------------------------------------------===//
// Primitive Module methods.
//
2001-10-13 06:58:40 +00:00
2014-02-25 20:01:08 +00:00
Module::Module(StringRef MID, LLVMContext &C)
: Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
2007-02-05 20:47:22 +00:00
ValSymTab = new ValueSymbolTable();
NamedMDSymTab = new StringMap<NamedMDNode *>();
Context.addModule(this);
2001-06-06 20:29:01 +00:00
}
Module::~Module() {
Context.removeModule(this);
2001-06-06 20:29:01 +00:00
dropAllReferences();
2002-06-25 16:13:24 +00:00
GlobalList.clear();
FunctionList.clear();
AliasList.clear();
2016-04-07 12:32:19 +00:00
IFuncList.clear();
NamedMDList.clear();
2007-01-06 07:24:44 +00:00
delete ValSymTab;
delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
2001-06-06 20:29:01 +00:00
}
RandomNumberGenerator *Module::createRNG(const Pass* P) const {
SmallString<32> Salt(P->getPassName());
// This RNG is guaranteed to produce the same random stream only
// when the Module ID and thus the input filename is the same. This
// might be problematic if the input filename extension changes
// (e.g. from .c to .bc or .ll).
//
// We could store this salt in NamedMetadata, but this would make
// the parameter non-const. This would unfortunately make this
// interface unusable by any Machine passes, since they only have a
// const reference to their IR Module. Alternatively we can always
// store salt metadata from the Module constructor.
Salt += sys::path::filename(getModuleIdentifier());
return new RandomNumberGenerator(Salt);
}
/// getNamedValue - Return the first global value in the module with
/// the specified name, of arbitrary type. This method returns null
/// if a global with the specified name is not found.
2009-11-06 10:58:06 +00:00
GlobalValue *Module::getNamedValue(StringRef Name) const {
return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
}
/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
/// This ID is uniqued across modules in the current LLVMContext.
unsigned Module::getMDKindID(StringRef Name) const {
return Context.getMDKindID(Name);
}
/// getMDKindNames - Populate client supplied SmallVector with the name for
/// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
/// so it is filled in as an empty string.
void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
return Context.getMDKindNames(Result);
}
void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
return Context.getOperandBundleTags(Result);
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the functions in the module.
//
2007-02-05 20:47:22 +00:00
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return
// it. This is nice because it allows most passes to get away with not handling
// the symbol table directly for this common task.
//
2009-11-06 10:58:06 +00:00
Constant *Module::getOrInsertFunction(StringRef Name,
FunctionType *Ty,
AttributeSet AttributeList) {
2007-02-05 20:47:22 +00:00
// See if we have a definition for the specified function already.
GlobalValue *F = getNamedValue(Name);
if (!F) {
2007-02-05 20:47:22 +00:00
// Nope, add it
Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
New->setAttributes(AttributeList);
FunctionList.push_back(New);
return New; // Return the new prototype.
}
// If the function exists but has the wrong type, return a bitcast to the
// right type.
2009-07-29 22:17:13 +00:00
if (F->getType() != PointerType::getUnqual(Ty))
return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
2012-04-23 00:23:33 +00:00
// Otherwise, we just found the existing function or a prototype.
2012-04-23 00:23:33 +00:00
return F;
}
2009-11-06 10:58:06 +00:00
Constant *Module::getOrInsertFunction(StringRef Name,
FunctionType *Ty) {
return getOrInsertFunction(Name, Ty, AttributeSet());
}
2003-08-31 00:19:28 +00:00
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return it.
// This version of the method takes a null terminated list of function
// arguments, which makes it easier for clients to use.
//
2009-11-06 10:58:06 +00:00
Constant *Module::getOrInsertFunction(StringRef Name,
AttributeSet AttributeList,
Type *RetTy, ...) {
va_list Args;
va_start(Args, RetTy);
// Build the list of argument types...
std::vector<Type*> ArgTys;
while (Type *ArgTy = va_arg(Args, Type*))
ArgTys.push_back(ArgTy);
va_end(Args);
// Build the function type and chain to the other getOrInsertFunction...
2009-07-08 23:50:31 +00:00
return getOrInsertFunction(Name,
2009-07-29 22:17:13 +00:00
FunctionType::get(RetTy, ArgTys, false),
AttributeList);
}
2009-11-06 10:58:06 +00:00
Constant *Module::getOrInsertFunction(StringRef Name,
Type *RetTy, ...) {
2003-08-31 00:19:28 +00:00
va_list Args;
va_start(Args, RetTy);
// Build the list of argument types...
std::vector<Type*> ArgTys;
while (Type *ArgTy = va_arg(Args, Type*))
2003-08-31 00:19:28 +00:00
ArgTys.push_back(ArgTy);
va_end(Args);
// Build the function type and chain to the other getOrInsertFunction...
2012-04-23 00:23:33 +00:00
return getOrInsertFunction(Name,
2009-07-29 22:17:13 +00:00
FunctionType::get(RetTy, ArgTys, false),
AttributeSet());
2003-08-31 00:19:28 +00:00
}
// getFunction - Look up the specified function in the module symbol table.
// If it does not exist, return null.
//
2009-11-06 10:58:06 +00:00
Function *Module::getFunction(StringRef Name) const {
return dyn_cast_or_null<Function>(getNamedValue(Name));
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the global variables in the module.
//
/// getGlobalVariable - Look up the specified global variable in the module
/// symbol table. If it does not exist, return null. The type argument
/// should be the underlying type of the global, i.e., it should not have
/// the top-level PointerType, which represents the address of the global.
2009-01-15 20:18:42 +00:00
/// If AllowLocal is set to true, this function will return types that
/// have an local. By default, these types are not returned.
///
2013-07-25 02:50:08 +00:00
GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
2012-04-23 00:23:33 +00:00
if (GlobalVariable *Result =
dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
if (AllowLocal || !Result->hasLocalLinkage())
return Result;
return nullptr;
}
2008-11-05 23:42:27 +00:00
/// getOrInsertGlobal - Look up the specified global in the module symbol table.
/// 1. If it does not exist, add a declaration of the global and return it.
/// 2. Else, the global exists but has the wrong type: return the function
/// with a constantexpr cast to the right type.
2013-09-28 01:08:00 +00:00
/// 3. Finally, if the existing global is the correct declaration, return the
2008-11-05 23:42:27 +00:00
/// existing global.
Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
// See if we have a definition for the specified global already.
GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
if (!GV) {
// Nope, add it
GlobalVariable *New =
new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
nullptr, Name);
return New; // Return the new declaration.
}
// If the variable exists but has the wrong type, return a bitcast to the
// right type.
Type *GVTy = GV->getType();
PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
2013-09-30 23:31:50 +00:00
if (GVTy != PTy)
return ConstantExpr::getBitCast(GV, PTy);
2012-04-23 00:23:33 +00:00
// Otherwise, we just found the existing function or a prototype.
return GV;
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the global variables in the module.
//
// getNamedAlias - Look up the specified global in the module symbol table.
// If it does not exist, return null.
//
2009-11-06 10:58:06 +00:00
GlobalAlias *Module::getNamedAlias(StringRef Name) const {
return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
}
2016-04-07 12:32:19 +00:00
GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
}
2009-07-30 23:59:04 +00:00
/// getNamedMetadata - Return the first NamedMDNode in the module with the
2012-04-23 00:23:33 +00:00
/// specified name. This method returns null if a NamedMDNode with the
2010-06-19 05:33:57 +00:00
/// specified name is not found.
NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
SmallString<256> NameData;
StringRef NameRef = Name.toStringRef(NameData);
return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
}
2012-04-23 00:23:33 +00:00
/// getOrInsertNamedMetadata - Return the first named MDNode in the module
/// with the specified name. This method returns a new NamedMDNode if a
2009-07-30 23:59:04 +00:00
/// NamedMDNode with the specified name is not found.
2009-11-06 10:58:06 +00:00
NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
NamedMDNode *&NMD =
(*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
if (!NMD) {
NMD = new NamedMDNode(Name);
NMD->setParent(this);
NamedMDList.push_back(NMD);
}
2009-07-30 23:59:04 +00:00
return NMD;
}
2012-02-11 11:38:06 +00:00
/// eraseNamedMetadata - Remove the given NamedMDNode from this module and
/// delete it.
void Module::eraseNamedMetadata(NamedMDNode *NMD) {
static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
NamedMDList.erase(NMD->getIterator());
}
2014-12-09 18:38:53 +00:00
bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
uint64_t Val = Behavior->getLimitedValue();
if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
MFB = static_cast<ModFlagBehavior>(Val);
return true;
}
}
return false;
}
/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
void Module::
getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
const NamedMDNode *ModFlags = getModuleFlagsMetadata();
if (!ModFlags) return;
2014-11-11 21:30:22 +00:00
for (const MDNode *Flag : ModFlags->operands()) {
ModFlagBehavior MFB;
if (Flag->getNumOperands() >= 3 &&
isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
// Check the operands of the MDNode before accessing the operands.
// The verifier will actually catch these failures.
MDString *Key = cast<MDString>(Flag->getOperand(1));
2014-12-09 18:38:53 +00:00
Metadata *Val = Flag->getOperand(2);
Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
}
}
}
/// Return the corresponding value if Key appears in module flags, otherwise
/// return null.
2014-12-09 18:38:53 +00:00
Metadata *Module::getModuleFlag(StringRef Key) const {
SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
getModuleFlagsMetadata(ModuleFlags);
2014-03-10 15:03:06 +00:00
for (const ModuleFlagEntry &MFE : ModuleFlags) {
if (Key == MFE.Key->getString())
return MFE.Val;
}
return nullptr;
}
2012-02-11 11:38:06 +00:00
/// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
/// represents module-level flags. This method returns null if there are no
/// module-level flags.
NamedMDNode *Module::getModuleFlagsMetadata() const {
return getNamedMetadata("llvm.module.flags");
}
/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
/// represents module-level flags. If module-level flags aren't found, it
/// creates the named metadata that contains them.
NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
return getOrInsertNamedMetadata("llvm.module.flags");
}
/// addModuleFlag - Add a module-level flag to the module-level flags
/// metadata. It will create the module-level flags named metadata if it doesn't
/// already exist.
void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
2014-12-09 18:38:53 +00:00
Metadata *Val) {
2012-02-11 11:38:06 +00:00
Type *Int32Ty = Type::getInt32Ty(Context);
2014-12-09 18:38:53 +00:00
Metadata *Ops[3] = {
ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
MDString::get(Context, Key), Val};
2012-02-11 11:38:06 +00:00
getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
}
2014-12-09 18:38:53 +00:00
void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
Constant *Val) {
addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
}
void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
2012-02-11 11:38:06 +00:00
uint32_t Val) {
Type *Int32Ty = Type::getInt32Ty(Context);
addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
}
void Module::addModuleFlag(MDNode *Node) {
assert(Node->getNumOperands() == 3 &&
"Invalid number of operands for module flag!");
2014-12-09 18:38:53 +00:00
assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
2012-02-11 11:38:06 +00:00
isa<MDString>(Node->getOperand(1)) &&
"Invalid operand types for module flag!");
getOrInsertModuleFlagsMetadata()->addOperand(Node);
}
2002-04-13 18:58:33 +00:00
2014-02-25 20:01:08 +00:00
void Module::setDataLayout(StringRef Desc) {
2014-02-25 22:23:04 +00:00
DL.reset(Desc);
2014-02-25 20:01:08 +00:00
}
2015-03-04 18:43:29 +00:00
void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
2014-02-25 20:01:08 +00:00
2015-03-04 18:43:29 +00:00
const DataLayout &Module::getDataLayout() const { return DL; }
2014-02-25 20:01:08 +00:00
DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
return cast<DICompileUnit>(CUs->getOperand(Idx));
}
DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
return cast<DICompileUnit>(CUs->getOperand(Idx));
}
void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
while (CUs && (Idx < CUs->getNumOperands()) &&
((*this)->getEmissionKind() == DICompileUnit::NoDebug))
++Idx;
}
//===----------------------------------------------------------------------===//
// Methods to control the materialization of GlobalValues in the Module.
//
void Module::setMaterializer(GVMaterializer *GVM) {
assert(!Materializer &&
2015-12-18 20:13:39 +00:00
"Module already has a GVMaterializer. Call materializeAll"
" to clear it out before setting another one.");
Materializer.reset(GVM);
}
Error Module::materialize(GlobalValue *GV) {
2013-11-05 19:36:34 +00:00
if (!Materializer)
return Error::success();
2013-11-05 19:36:34 +00:00
return Materializer->materialize(GV);
}
Error Module::materializeAll() {
if (!Materializer)
return Error::success();
std::unique_ptr<GVMaterializer> M = std::move(Materializer);
return M->materializeModule();
}
Error Module::materializeMetadata() {
if (!Materializer)
return Error::success();
return Materializer->materializeMetadata();
}
//===----------------------------------------------------------------------===//
// Other module related stuff.
//
std::vector<StructType *> Module::getIdentifiedStructTypes() const {
// If we have a materializer, it is possible that some unread function
// uses a type that is currently not visible to a TypeFinder, so ask
// the materializer which types it created.
if (Materializer)
return Materializer->getIdentifiedStructTypes();
std::vector<StructType *> Ret;
TypeFinder SrcStructTypes;
SrcStructTypes.run(*this, true);
Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
return Ret;
}
2012-04-16 23:54:31 +00:00
// dropAllReferences() - This function causes all the subelements to "let go"
2002-08-17 23:32:47 +00:00
// of all references that they are maintaining. This allows one to 'delete' a
// whole module at a time, even though there may be circular references... first
// all references are dropped, and all use counts go to zero. Then everything
2003-10-10 17:54:14 +00:00
// is deleted for real. Note that no operations are valid on an object that
2002-08-17 23:32:47 +00:00
// has "dropped all references", except operator delete.
2001-06-06 20:29:01 +00:00
//
void Module::dropAllReferences() {
2014-07-03 16:12:55 +00:00
for (Function &F : *this)
F.dropAllReferences();
2001-10-13 06:58:40 +00:00
2014-07-03 16:12:55 +00:00
for (GlobalVariable &GV : globals())
GV.dropAllReferences();
2014-07-03 16:12:55 +00:00
for (GlobalAlias &GA : aliases())
GA.dropAllReferences();
2016-04-07 12:32:19 +00:00
for (GlobalIFunc &GIF : ifuncs())
GIF.dropAllReferences();
2001-06-06 20:29:01 +00:00
}
unsigned Module::getDwarfVersion() const {
2014-12-09 18:38:53 +00:00
auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
if (!Val)
return 0;
return cast<ConstantInt>(Val->getValue())->getZExtValue();
}
unsigned Module::getCodeViewFlag() const {
auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
if (!Val)
return 0;
2014-12-09 18:38:53 +00:00
return cast<ConstantInt>(Val->getValue())->getZExtValue();
}
2014-06-27 18:19:56 +00:00
Comdat *Module::getOrInsertComdat(StringRef Name) {
auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
2014-06-27 18:19:56 +00:00
Entry.second.Name = &Entry;
return &Entry.second;
}
PICLevel::Level Module::getPICLevel() const {
2014-12-09 18:38:53 +00:00
auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
if (!Val)
2016-06-17 18:07:14 +00:00
return PICLevel::NotPIC;
2014-12-09 18:38:53 +00:00
return static_cast<PICLevel::Level>(
cast<ConstantInt>(Val->getValue())->getZExtValue());
}
void Module::setPICLevel(PICLevel::Level PL) {
addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
}
2016-04-28 18:15:44 +00:00
PIELevel::Level Module::getPIELevel() const {
auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
if (!Val)
return PIELevel::Default;
return static_cast<PIELevel::Level>(
cast<ConstantInt>(Val->getValue())->getZExtValue());
}
void Module::setPIELevel(PIELevel::Level PL) {
addModuleFlag(ModFlagBehavior::Error, "PIE Level", PL);
}
void Module::setProfileSummary(Metadata *M) {
addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
}
Metadata *Module::getProfileSummary() {
return getModuleFlag("ProfileSummary");
}
void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
OwnedMemoryBuffer = std::move(MB);
}
GlobalVariable *llvm::collectUsedGlobalVariables(
const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
GlobalVariable *GV = M.getGlobalVariable(Name);
if (!GV || !GV->hasInitializer())
return GV;
const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
for (Value *Op : Init->operands()) {
GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
Set.insert(G);
}
return GV;
}