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/STLExtras.h"
17 #include "llvm/ADT/SmallPtrSet.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/DebugInfoMetadata.h"
23 #include "llvm/IR/GVMaterializer.h"
24 #include "llvm/IR/InstrTypes.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/TypeFinder.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/Error.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/RandomNumberGenerator.h"
38 //===----------------------------------------------------------------------===//
39 // Methods to implement the globals and functions lists.
42 // Explicit instantiations of SymbolTableListTraits since some of the methods
43 // are not in the public header file.
44 template class llvm::SymbolTableListTraits<Function>;
45 template class llvm::SymbolTableListTraits<GlobalVariable>;
46 template class llvm::SymbolTableListTraits<GlobalAlias>;
47 template class llvm::SymbolTableListTraits<GlobalIFunc>;
49 //===----------------------------------------------------------------------===//
50 // Primitive Module methods.
53 Module::Module(StringRef MID, LLVMContext &C)
54 : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
55 ValSymTab = new ValueSymbolTable();
56 NamedMDSymTab = new StringMap<NamedMDNode *>();
57 Context.addModule(this);
61 Context.removeModule(this);
69 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
72 RandomNumberGenerator *Module::createRNG(const Pass* P) const {
73 SmallString<32> Salt(P->getPassName());
75 // This RNG is guaranteed to produce the same random stream only
76 // when the Module ID and thus the input filename is the same. This
77 // might be problematic if the input filename extension changes
78 // (e.g. from .c to .bc or .ll).
80 // We could store this salt in NamedMetadata, but this would make
81 // the parameter non-const. This would unfortunately make this
82 // interface unusable by any Machine passes, since they only have a
83 // const reference to their IR Module. Alternatively we can always
84 // store salt metadata from the Module constructor.
85 Salt += sys::path::filename(getModuleIdentifier());
87 return new RandomNumberGenerator(Salt);
90 /// getNamedValue - Return the first global value in the module with
91 /// the specified name, of arbitrary type. This method returns null
92 /// if a global with the specified name is not found.
93 GlobalValue *Module::getNamedValue(StringRef Name) const {
94 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
97 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
98 /// This ID is uniqued across modules in the current LLVMContext.
99 unsigned Module::getMDKindID(StringRef Name) const {
100 return Context.getMDKindID(Name);
103 /// getMDKindNames - Populate client supplied SmallVector with the name for
104 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
105 /// so it is filled in as an empty string.
106 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
107 return Context.getMDKindNames(Result);
110 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
111 return Context.getOperandBundleTags(Result);
114 //===----------------------------------------------------------------------===//
115 // Methods for easy access to the functions in the module.
118 // getOrInsertFunction - Look up the specified function in the module symbol
119 // table. If it does not exist, add a prototype for the function and return
120 // it. This is nice because it allows most passes to get away with not handling
121 // the symbol table directly for this common task.
123 Constant *Module::getOrInsertFunction(StringRef Name,
125 AttributeSet AttributeList) {
126 // See if we have a definition for the specified function already.
127 GlobalValue *F = getNamedValue(Name);
130 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
131 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
132 New->setAttributes(AttributeList);
133 FunctionList.push_back(New);
134 return New; // Return the new prototype.
137 // If the function exists but has the wrong type, return a bitcast to the
139 if (F->getType() != PointerType::getUnqual(Ty))
140 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
142 // Otherwise, we just found the existing function or a prototype.
146 Constant *Module::getOrInsertFunction(StringRef Name,
148 return getOrInsertFunction(Name, Ty, AttributeSet());
151 // getOrInsertFunction - Look up the specified function in the module symbol
152 // table. If it does not exist, add a prototype for the function and return it.
153 // This version of the method takes a null terminated list of function
154 // arguments, which makes it easier for clients to use.
156 Constant *Module::getOrInsertFunction(StringRef Name,
157 AttributeSet AttributeList,
160 va_start(Args, RetTy);
162 // Build the list of argument types...
163 std::vector<Type*> ArgTys;
164 while (Type *ArgTy = va_arg(Args, Type*))
165 ArgTys.push_back(ArgTy);
169 // Build the function type and chain to the other getOrInsertFunction...
170 return getOrInsertFunction(Name,
171 FunctionType::get(RetTy, ArgTys, false),
175 Constant *Module::getOrInsertFunction(StringRef Name,
178 va_start(Args, RetTy);
180 // Build the list of argument types...
181 std::vector<Type*> ArgTys;
182 while (Type *ArgTy = va_arg(Args, Type*))
183 ArgTys.push_back(ArgTy);
187 // Build the function type and chain to the other getOrInsertFunction...
188 return getOrInsertFunction(Name,
189 FunctionType::get(RetTy, ArgTys, false),
193 // getFunction - Look up the specified function in the module symbol table.
194 // If it does not exist, return null.
196 Function *Module::getFunction(StringRef Name) const {
197 return dyn_cast_or_null<Function>(getNamedValue(Name));
200 //===----------------------------------------------------------------------===//
201 // Methods for easy access to the global variables in the module.
204 /// getGlobalVariable - Look up the specified global variable in the module
205 /// symbol table. If it does not exist, return null. The type argument
206 /// should be the underlying type of the global, i.e., it should not have
207 /// the top-level PointerType, which represents the address of the global.
208 /// If AllowLocal is set to true, this function will return types that
209 /// have an local. By default, these types are not returned.
211 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
212 if (GlobalVariable *Result =
213 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
214 if (AllowLocal || !Result->hasLocalLinkage())
219 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
220 /// 1. If it does not exist, add a declaration of the global and return it.
221 /// 2. Else, the global exists but has the wrong type: return the function
222 /// with a constantexpr cast to the right type.
223 /// 3. Finally, if the existing global is the correct declaration, return the
225 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
226 // See if we have a definition for the specified global already.
227 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
230 GlobalVariable *New =
231 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
233 return New; // Return the new declaration.
236 // If the variable exists but has the wrong type, return a bitcast to the
238 Type *GVTy = GV->getType();
239 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
241 return ConstantExpr::getBitCast(GV, PTy);
243 // Otherwise, we just found the existing function or a prototype.
247 //===----------------------------------------------------------------------===//
248 // Methods for easy access to the global variables in the module.
251 // getNamedAlias - Look up the specified global in the module symbol table.
252 // If it does not exist, return null.
254 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
255 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
258 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
259 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
262 /// getNamedMetadata - Return the first NamedMDNode in the module with the
263 /// specified name. This method returns null if a NamedMDNode with the
264 /// specified name is not found.
265 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
266 SmallString<256> NameData;
267 StringRef NameRef = Name.toStringRef(NameData);
268 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
271 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
272 /// with the specified name. This method returns a new NamedMDNode if a
273 /// NamedMDNode with the specified name is not found.
274 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
276 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
278 NMD = new NamedMDNode(Name);
279 NMD->setParent(this);
280 NamedMDList.push_back(NMD);
285 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
287 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
288 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
289 NamedMDList.erase(NMD->getIterator());
292 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
293 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
294 uint64_t Val = Behavior->getLimitedValue();
295 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
296 MFB = static_cast<ModFlagBehavior>(Val);
303 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
305 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
306 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
307 if (!ModFlags) return;
309 for (const MDNode *Flag : ModFlags->operands()) {
311 if (Flag->getNumOperands() >= 3 &&
312 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
313 dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
314 // Check the operands of the MDNode before accessing the operands.
315 // The verifier will actually catch these failures.
316 MDString *Key = cast<MDString>(Flag->getOperand(1));
317 Metadata *Val = Flag->getOperand(2);
318 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
323 /// Return the corresponding value if Key appears in module flags, otherwise
325 Metadata *Module::getModuleFlag(StringRef Key) const {
326 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
327 getModuleFlagsMetadata(ModuleFlags);
328 for (const ModuleFlagEntry &MFE : ModuleFlags) {
329 if (Key == MFE.Key->getString())
335 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
336 /// represents module-level flags. This method returns null if there are no
337 /// module-level flags.
338 NamedMDNode *Module::getModuleFlagsMetadata() const {
339 return getNamedMetadata("llvm.module.flags");
342 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
343 /// represents module-level flags. If module-level flags aren't found, it
344 /// creates the named metadata that contains them.
345 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
346 return getOrInsertNamedMetadata("llvm.module.flags");
349 /// addModuleFlag - Add a module-level flag to the module-level flags
350 /// metadata. It will create the module-level flags named metadata if it doesn't
352 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
354 Type *Int32Ty = Type::getInt32Ty(Context);
356 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
357 MDString::get(Context, Key), Val};
358 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
360 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
362 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
364 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
366 Type *Int32Ty = Type::getInt32Ty(Context);
367 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
369 void Module::addModuleFlag(MDNode *Node) {
370 assert(Node->getNumOperands() == 3 &&
371 "Invalid number of operands for module flag!");
372 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
373 isa<MDString>(Node->getOperand(1)) &&
374 "Invalid operand types for module flag!");
375 getOrInsertModuleFlagsMetadata()->addOperand(Node);
378 void Module::setDataLayout(StringRef Desc) {
382 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
384 const DataLayout &Module::getDataLayout() const { return DL; }
386 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
387 return cast<DICompileUnit>(CUs->getOperand(Idx));
389 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
390 return cast<DICompileUnit>(CUs->getOperand(Idx));
393 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
394 while (CUs && (Idx < CUs->getNumOperands()) &&
395 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
399 //===----------------------------------------------------------------------===//
400 // Methods to control the materialization of GlobalValues in the Module.
402 void Module::setMaterializer(GVMaterializer *GVM) {
403 assert(!Materializer &&
404 "Module already has a GVMaterializer. Call materializeAll"
405 " to clear it out before setting another one.");
406 Materializer.reset(GVM);
409 Error Module::materialize(GlobalValue *GV) {
411 return Error::success();
413 return Materializer->materialize(GV);
416 Error Module::materializeAll() {
418 return Error::success();
419 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
420 return M->materializeModule();
423 Error Module::materializeMetadata() {
425 return Error::success();
426 return Materializer->materializeMetadata();
429 //===----------------------------------------------------------------------===//
430 // Other module related stuff.
433 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
434 // If we have a materializer, it is possible that some unread function
435 // uses a type that is currently not visible to a TypeFinder, so ask
436 // the materializer which types it created.
438 return Materializer->getIdentifiedStructTypes();
440 std::vector<StructType *> Ret;
441 TypeFinder SrcStructTypes;
442 SrcStructTypes.run(*this, true);
443 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
447 // dropAllReferences() - This function causes all the subelements to "let go"
448 // of all references that they are maintaining. This allows one to 'delete' a
449 // whole module at a time, even though there may be circular references... first
450 // all references are dropped, and all use counts go to zero. Then everything
451 // is deleted for real. Note that no operations are valid on an object that
452 // has "dropped all references", except operator delete.
454 void Module::dropAllReferences() {
455 for (Function &F : *this)
456 F.dropAllReferences();
458 for (GlobalVariable &GV : globals())
459 GV.dropAllReferences();
461 for (GlobalAlias &GA : aliases())
462 GA.dropAllReferences();
464 for (GlobalIFunc &GIF : ifuncs())
465 GIF.dropAllReferences();
468 unsigned Module::getDwarfVersion() const {
469 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
472 return cast<ConstantInt>(Val->getValue())->getZExtValue();
475 unsigned Module::getCodeViewFlag() const {
476 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
479 return cast<ConstantInt>(Val->getValue())->getZExtValue();
482 Comdat *Module::getOrInsertComdat(StringRef Name) {
483 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
484 Entry.second.Name = &Entry;
485 return &Entry.second;
488 PICLevel::Level Module::getPICLevel() const {
489 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
492 return PICLevel::NotPIC;
494 return static_cast<PICLevel::Level>(
495 cast<ConstantInt>(Val->getValue())->getZExtValue());
498 void Module::setPICLevel(PICLevel::Level PL) {
499 addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
502 PIELevel::Level Module::getPIELevel() const {
503 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
506 return PIELevel::Default;
508 return static_cast<PIELevel::Level>(
509 cast<ConstantInt>(Val->getValue())->getZExtValue());
512 void Module::setPIELevel(PIELevel::Level PL) {
513 addModuleFlag(ModFlagBehavior::Error, "PIE Level", PL);
516 void Module::setProfileSummary(Metadata *M) {
517 addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
520 Metadata *Module::getProfileSummary() {
521 return getModuleFlag("ProfileSummary");
524 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
525 OwnedMemoryBuffer = std::move(MB);
528 GlobalVariable *llvm::collectUsedGlobalVariables(
529 const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
530 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
531 GlobalVariable *GV = M.getGlobalVariable(Name);
532 if (!GV || !GV->hasInitializer())
535 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
536 for (Value *Op : Init->operands()) {
537 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());