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 IR library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Module.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GVMaterializer.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/LeakDetector.h"
26 #include "llvm/Support/Dwarf.h"
31 using std::error_code;
33 //===----------------------------------------------------------------------===//
34 // Methods to implement the globals and functions lists.
37 // Explicit instantiations of SymbolTableListTraits since some of the methods
38 // are not in the public header file.
39 template class llvm::SymbolTableListTraits<Function, Module>;
40 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
41 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
43 //===----------------------------------------------------------------------===//
44 // Primitive Module methods.
47 Module::Module(StringRef MID, LLVMContext &C)
48 : Context(C), Materializer(), ModuleID(MID), DL("") {
49 ValSymTab = new ValueSymbolTable();
50 NamedMDSymTab = new StringMap<NamedMDNode *>();
51 Context.addModule(this);
55 Context.removeModule(this);
62 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
65 /// getNamedValue - Return the first global value in the module with
66 /// the specified name, of arbitrary type. This method returns null
67 /// if a global with the specified name is not found.
68 GlobalValue *Module::getNamedValue(StringRef Name) const {
69 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
72 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
73 /// This ID is uniqued across modules in the current LLVMContext.
74 unsigned Module::getMDKindID(StringRef Name) const {
75 return Context.getMDKindID(Name);
78 /// getMDKindNames - Populate client supplied SmallVector with the name for
79 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
80 /// so it is filled in as an empty string.
81 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
82 return Context.getMDKindNames(Result);
86 //===----------------------------------------------------------------------===//
87 // Methods for easy access to the functions in the module.
90 // getOrInsertFunction - Look up the specified function in the module symbol
91 // table. If it does not exist, add a prototype for the function and return
92 // it. This is nice because it allows most passes to get away with not handling
93 // the symbol table directly for this common task.
95 Constant *Module::getOrInsertFunction(StringRef Name,
97 AttributeSet AttributeList) {
98 // See if we have a definition for the specified function already.
99 GlobalValue *F = getNamedValue(Name);
102 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
103 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
104 New->setAttributes(AttributeList);
105 FunctionList.push_back(New);
106 return New; // Return the new prototype.
109 // If the function exists but has the wrong type, return a bitcast to the
111 if (F->getType() != PointerType::getUnqual(Ty))
112 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
114 // Otherwise, we just found the existing function or a prototype.
118 Constant *Module::getOrInsertFunction(StringRef Name,
120 return getOrInsertFunction(Name, Ty, AttributeSet());
123 // getOrInsertFunction - Look up the specified function in the module symbol
124 // table. If it does not exist, add a prototype for the function and return it.
125 // This version of the method takes a null terminated list of function
126 // arguments, which makes it easier for clients to use.
128 Constant *Module::getOrInsertFunction(StringRef Name,
129 AttributeSet AttributeList,
132 va_start(Args, RetTy);
134 // Build the list of argument types...
135 std::vector<Type*> ArgTys;
136 while (Type *ArgTy = va_arg(Args, Type*))
137 ArgTys.push_back(ArgTy);
141 // Build the function type and chain to the other getOrInsertFunction...
142 return getOrInsertFunction(Name,
143 FunctionType::get(RetTy, ArgTys, false),
147 Constant *Module::getOrInsertFunction(StringRef Name,
150 va_start(Args, RetTy);
152 // Build the list of argument types...
153 std::vector<Type*> ArgTys;
154 while (Type *ArgTy = va_arg(Args, Type*))
155 ArgTys.push_back(ArgTy);
159 // Build the function type and chain to the other getOrInsertFunction...
160 return getOrInsertFunction(Name,
161 FunctionType::get(RetTy, ArgTys, false),
165 // getFunction - Look up the specified function in the module symbol table.
166 // If it does not exist, return null.
168 Function *Module::getFunction(StringRef Name) const {
169 return dyn_cast_or_null<Function>(getNamedValue(Name));
172 //===----------------------------------------------------------------------===//
173 // Methods for easy access to the global variables in the module.
176 /// getGlobalVariable - Look up the specified global variable in the module
177 /// symbol table. If it does not exist, return null. The type argument
178 /// should be the underlying type of the global, i.e., it should not have
179 /// the top-level PointerType, which represents the address of the global.
180 /// If AllowLocal is set to true, this function will return types that
181 /// have an local. By default, these types are not returned.
183 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
184 if (GlobalVariable *Result =
185 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
186 if (AllowLocal || !Result->hasLocalLinkage())
191 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
192 /// 1. If it does not exist, add a declaration of the global and return it.
193 /// 2. Else, the global exists but has the wrong type: return the function
194 /// with a constantexpr cast to the right type.
195 /// 3. Finally, if the existing global is the correct declaration, return the
197 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
198 // See if we have a definition for the specified global already.
199 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
202 GlobalVariable *New =
203 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
205 return New; // Return the new declaration.
208 // If the variable exists but has the wrong type, return a bitcast to the
210 Type *GVTy = GV->getType();
211 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
213 return ConstantExpr::getBitCast(GV, PTy);
215 // Otherwise, we just found the existing function or a prototype.
219 //===----------------------------------------------------------------------===//
220 // Methods for easy access to the global variables in the module.
223 // getNamedAlias - Look up the specified global in the module symbol table.
224 // If it does not exist, return null.
226 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
227 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
230 /// getNamedMetadata - Return the first NamedMDNode in the module with the
231 /// specified name. This method returns null if a NamedMDNode with the
232 /// specified name is not found.
233 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
234 SmallString<256> NameData;
235 StringRef NameRef = Name.toStringRef(NameData);
236 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
239 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
240 /// with the specified name. This method returns a new NamedMDNode if a
241 /// NamedMDNode with the specified name is not found.
242 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
244 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
246 NMD = new NamedMDNode(Name);
247 NMD->setParent(this);
248 NamedMDList.push_back(NMD);
253 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
255 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
256 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
257 NamedMDList.erase(NMD);
260 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
262 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
263 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
264 if (!ModFlags) return;
266 for (const MDNode *Flag : ModFlags->operands()) {
267 if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) &&
268 isa<MDString>(Flag->getOperand(1))) {
269 // Check the operands of the MDNode before accessing the operands.
270 // The verifier will actually catch these failures.
271 ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
272 MDString *Key = cast<MDString>(Flag->getOperand(1));
273 Value *Val = Flag->getOperand(2);
274 Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
280 /// Return the corresponding value if Key appears in module flags, otherwise
282 Value *Module::getModuleFlag(StringRef Key) const {
283 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
284 getModuleFlagsMetadata(ModuleFlags);
285 for (const ModuleFlagEntry &MFE : ModuleFlags) {
286 if (Key == MFE.Key->getString())
292 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
293 /// represents module-level flags. This method returns null if there are no
294 /// module-level flags.
295 NamedMDNode *Module::getModuleFlagsMetadata() const {
296 return getNamedMetadata("llvm.module.flags");
299 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
300 /// represents module-level flags. If module-level flags aren't found, it
301 /// creates the named metadata that contains them.
302 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
303 return getOrInsertNamedMetadata("llvm.module.flags");
306 /// addModuleFlag - Add a module-level flag to the module-level flags
307 /// metadata. It will create the module-level flags named metadata if it doesn't
309 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
311 Type *Int32Ty = Type::getInt32Ty(Context);
313 ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
315 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
317 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
319 Type *Int32Ty = Type::getInt32Ty(Context);
320 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
322 void Module::addModuleFlag(MDNode *Node) {
323 assert(Node->getNumOperands() == 3 &&
324 "Invalid number of operands for module flag!");
325 assert(isa<ConstantInt>(Node->getOperand(0)) &&
326 isa<MDString>(Node->getOperand(1)) &&
327 "Invalid operand types for module flag!");
328 getOrInsertModuleFlagsMetadata()->addOperand(Node);
331 void Module::setDataLayout(StringRef Desc) {
337 DataLayoutStr = DL.getStringRepresentation();
338 // DataLayoutStr is now equivalent to Desc, but since the representation
339 // is not unique, they may not be identical.
343 void Module::setDataLayout(const DataLayout *Other) {
349 DataLayoutStr = DL.getStringRepresentation();
353 const DataLayout *Module::getDataLayout() const {
354 if (DataLayoutStr.empty())
359 //===----------------------------------------------------------------------===//
360 // Methods to control the materialization of GlobalValues in the Module.
362 void Module::setMaterializer(GVMaterializer *GVM) {
363 assert(!Materializer &&
364 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
365 " to clear it out before setting another one.");
366 Materializer.reset(GVM);
369 bool Module::isMaterializable(const GlobalValue *GV) const {
371 return Materializer->isMaterializable(GV);
375 bool Module::isDematerializable(const GlobalValue *GV) const {
377 return Materializer->isDematerializable(GV);
381 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
385 error_code EC = Materializer->Materialize(GV);
389 *ErrInfo = EC.message();
393 void Module::Dematerialize(GlobalValue *GV) {
395 return Materializer->Dematerialize(GV);
398 error_code Module::materializeAll() {
401 return Materializer->MaterializeModule(this);
404 error_code Module::materializeAllPermanently() {
405 if (error_code EC = materializeAll())
408 Materializer.reset();
412 //===----------------------------------------------------------------------===//
413 // Other module related stuff.
417 // dropAllReferences() - This function causes all the subelements to "let go"
418 // of all references that they are maintaining. This allows one to 'delete' a
419 // whole module at a time, even though there may be circular references... first
420 // all references are dropped, and all use counts go to zero. Then everything
421 // is deleted for real. Note that no operations are valid on an object that
422 // has "dropped all references", except operator delete.
424 void Module::dropAllReferences() {
425 for(Module::iterator I = begin(), E = end(); I != E; ++I)
426 I->dropAllReferences();
428 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
429 I->dropAllReferences();
431 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
432 I->dropAllReferences();
435 unsigned Module::getDwarfVersion() const {
436 Value *Val = getModuleFlag("Dwarf Version");
438 return dwarf::DWARF_VERSION;
439 return cast<ConstantInt>(Val)->getZExtValue();