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/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/Attributes.h"
23 #include "llvm/IR/Comdat.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GVMaterializer.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalIFunc.h"
32 #include "llvm/IR/GlobalValue.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/SymbolTableListTraits.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/TypeFinder.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/IR/ValueSymbolTable.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CodeGen.h"
44 #include "llvm/Support/Error.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/RandomNumberGenerator.h"
57 //===----------------------------------------------------------------------===//
58 // Methods to implement the globals and functions lists.
61 // Explicit instantiations of SymbolTableListTraits since some of the methods
62 // are not in the public header file.
63 template class llvm::SymbolTableListTraits<Function>;
64 template class llvm::SymbolTableListTraits<GlobalVariable>;
65 template class llvm::SymbolTableListTraits<GlobalAlias>;
66 template class llvm::SymbolTableListTraits<GlobalIFunc>;
68 //===----------------------------------------------------------------------===//
69 // Primitive Module methods.
72 Module::Module(StringRef MID, LLVMContext &C)
73 : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
74 ValSymTab = new ValueSymbolTable();
75 NamedMDSymTab = new StringMap<NamedMDNode *>();
76 Context.addModule(this);
80 Context.removeModule(this);
88 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
91 std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
92 SmallString<32> Salt(P->getPassName());
94 // This RNG is guaranteed to produce the same random stream only
95 // when the Module ID and thus the input filename is the same. This
96 // might be problematic if the input filename extension changes
97 // (e.g. from .c to .bc or .ll).
99 // We could store this salt in NamedMetadata, but this would make
100 // the parameter non-const. This would unfortunately make this
101 // interface unusable by any Machine passes, since they only have a
102 // const reference to their IR Module. Alternatively we can always
103 // store salt metadata from the Module constructor.
104 Salt += sys::path::filename(getModuleIdentifier());
106 return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt));
109 /// getNamedValue - Return the first global value in the module with
110 /// the specified name, of arbitrary type. This method returns null
111 /// if a global with the specified name is not found.
112 GlobalValue *Module::getNamedValue(StringRef Name) const {
113 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
116 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
117 /// This ID is uniqued across modules in the current LLVMContext.
118 unsigned Module::getMDKindID(StringRef Name) const {
119 return Context.getMDKindID(Name);
122 /// getMDKindNames - Populate client supplied SmallVector with the name for
123 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
124 /// so it is filled in as an empty string.
125 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
126 return Context.getMDKindNames(Result);
129 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
130 return Context.getOperandBundleTags(Result);
133 //===----------------------------------------------------------------------===//
134 // Methods for easy access to the functions in the module.
137 // getOrInsertFunction - Look up the specified function in the module symbol
138 // table. If it does not exist, add a prototype for the function and return
139 // it. This is nice because it allows most passes to get away with not handling
140 // the symbol table directly for this common task.
142 Constant *Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
143 AttributeList AttributeList) {
144 // See if we have a definition for the specified function already.
145 GlobalValue *F = getNamedValue(Name);
148 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
149 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
150 New->setAttributes(AttributeList);
151 FunctionList.push_back(New);
152 return New; // Return the new prototype.
155 // If the function exists but has the wrong type, return a bitcast to the
157 if (F->getType() != PointerType::getUnqual(Ty))
158 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
160 // Otherwise, we just found the existing function or a prototype.
164 Constant *Module::getOrInsertFunction(StringRef Name,
166 return getOrInsertFunction(Name, Ty, AttributeList());
169 // getFunction - Look up the specified function in the module symbol table.
170 // If it does not exist, return null.
172 Function *Module::getFunction(StringRef Name) const {
173 return dyn_cast_or_null<Function>(getNamedValue(Name));
176 //===----------------------------------------------------------------------===//
177 // Methods for easy access to the global variables in the module.
180 /// getGlobalVariable - Look up the specified global variable in the module
181 /// symbol table. If it does not exist, return null. The type argument
182 /// should be the underlying type of the global, i.e., it should not have
183 /// the top-level PointerType, which represents the address of the global.
184 /// If AllowLocal is set to true, this function will return types that
185 /// have an local. By default, these types are not returned.
187 GlobalVariable *Module::getGlobalVariable(StringRef Name,
188 bool AllowLocal) const {
189 if (GlobalVariable *Result =
190 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
191 if (AllowLocal || !Result->hasLocalLinkage())
196 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
197 /// 1. If it does not exist, add a declaration of the global and return it.
198 /// 2. Else, the global exists but has the wrong type: return the function
199 /// with a constantexpr cast to the right type.
200 /// 3. Finally, if the existing global is the correct declaration, return the
202 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
203 // See if we have a definition for the specified global already.
204 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
207 GlobalVariable *New =
208 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
210 return New; // Return the new declaration.
213 // If the variable exists but has the wrong type, return a bitcast to the
215 Type *GVTy = GV->getType();
216 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
218 return ConstantExpr::getBitCast(GV, PTy);
220 // Otherwise, we just found the existing function or a prototype.
224 //===----------------------------------------------------------------------===//
225 // Methods for easy access to the global variables in the module.
228 // getNamedAlias - Look up the specified global in the module symbol table.
229 // If it does not exist, return null.
231 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
232 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
235 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
236 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
239 /// getNamedMetadata - Return the first NamedMDNode in the module with the
240 /// specified name. This method returns null if a NamedMDNode with the
241 /// specified name is not found.
242 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
243 SmallString<256> NameData;
244 StringRef NameRef = Name.toStringRef(NameData);
245 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
248 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
249 /// with the specified name. This method returns a new NamedMDNode if a
250 /// NamedMDNode with the specified name is not found.
251 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
253 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
255 NMD = new NamedMDNode(Name);
256 NMD->setParent(this);
257 NamedMDList.push_back(NMD);
262 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
264 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
265 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
266 NamedMDList.erase(NMD->getIterator());
269 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
270 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
271 uint64_t Val = Behavior->getLimitedValue();
272 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
273 MFB = static_cast<ModFlagBehavior>(Val);
280 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
282 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
283 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
284 if (!ModFlags) return;
286 for (const MDNode *Flag : ModFlags->operands()) {
288 if (Flag->getNumOperands() >= 3 &&
289 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
290 dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
291 // Check the operands of the MDNode before accessing the operands.
292 // The verifier will actually catch these failures.
293 MDString *Key = cast<MDString>(Flag->getOperand(1));
294 Metadata *Val = Flag->getOperand(2);
295 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
300 /// Return the corresponding value if Key appears in module flags, otherwise
302 Metadata *Module::getModuleFlag(StringRef Key) const {
303 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
304 getModuleFlagsMetadata(ModuleFlags);
305 for (const ModuleFlagEntry &MFE : ModuleFlags) {
306 if (Key == MFE.Key->getString())
312 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
313 /// represents module-level flags. This method returns null if there are no
314 /// module-level flags.
315 NamedMDNode *Module::getModuleFlagsMetadata() const {
316 return getNamedMetadata("llvm.module.flags");
319 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
320 /// represents module-level flags. If module-level flags aren't found, it
321 /// creates the named metadata that contains them.
322 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
323 return getOrInsertNamedMetadata("llvm.module.flags");
326 /// addModuleFlag - Add a module-level flag to the module-level flags
327 /// metadata. It will create the module-level flags named metadata if it doesn't
329 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
331 Type *Int32Ty = Type::getInt32Ty(Context);
333 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
334 MDString::get(Context, Key), Val};
335 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
337 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
339 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
341 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
343 Type *Int32Ty = Type::getInt32Ty(Context);
344 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
346 void Module::addModuleFlag(MDNode *Node) {
347 assert(Node->getNumOperands() == 3 &&
348 "Invalid number of operands for module flag!");
349 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
350 isa<MDString>(Node->getOperand(1)) &&
351 "Invalid operand types for module flag!");
352 getOrInsertModuleFlagsMetadata()->addOperand(Node);
355 void Module::setDataLayout(StringRef Desc) {
359 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
361 const DataLayout &Module::getDataLayout() const { return DL; }
363 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
364 return cast<DICompileUnit>(CUs->getOperand(Idx));
366 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
367 return cast<DICompileUnit>(CUs->getOperand(Idx));
370 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
371 while (CUs && (Idx < CUs->getNumOperands()) &&
372 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
376 //===----------------------------------------------------------------------===//
377 // Methods to control the materialization of GlobalValues in the Module.
379 void Module::setMaterializer(GVMaterializer *GVM) {
380 assert(!Materializer &&
381 "Module already has a GVMaterializer. Call materializeAll"
382 " to clear it out before setting another one.");
383 Materializer.reset(GVM);
386 Error Module::materialize(GlobalValue *GV) {
388 return Error::success();
390 return Materializer->materialize(GV);
393 Error Module::materializeAll() {
395 return Error::success();
396 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
397 return M->materializeModule();
400 Error Module::materializeMetadata() {
402 return Error::success();
403 return Materializer->materializeMetadata();
406 //===----------------------------------------------------------------------===//
407 // Other module related stuff.
410 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
411 // If we have a materializer, it is possible that some unread function
412 // uses a type that is currently not visible to a TypeFinder, so ask
413 // the materializer which types it created.
415 return Materializer->getIdentifiedStructTypes();
417 std::vector<StructType *> Ret;
418 TypeFinder SrcStructTypes;
419 SrcStructTypes.run(*this, true);
420 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
424 // dropAllReferences() - This function causes all the subelements to "let go"
425 // of all references that they are maintaining. This allows one to 'delete' a
426 // whole module at a time, even though there may be circular references... first
427 // all references are dropped, and all use counts go to zero. Then everything
428 // is deleted for real. Note that no operations are valid on an object that
429 // has "dropped all references", except operator delete.
431 void Module::dropAllReferences() {
432 for (Function &F : *this)
433 F.dropAllReferences();
435 for (GlobalVariable &GV : globals())
436 GV.dropAllReferences();
438 for (GlobalAlias &GA : aliases())
439 GA.dropAllReferences();
441 for (GlobalIFunc &GIF : ifuncs())
442 GIF.dropAllReferences();
445 unsigned Module::getNumberRegisterParameters() const {
447 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
450 return cast<ConstantInt>(Val->getValue())->getZExtValue();
453 unsigned Module::getDwarfVersion() const {
454 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
457 return cast<ConstantInt>(Val->getValue())->getZExtValue();
460 unsigned Module::getCodeViewFlag() const {
461 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
464 return cast<ConstantInt>(Val->getValue())->getZExtValue();
467 unsigned Module::getInstructionCount() {
468 unsigned NumInstrs = 0;
469 for (Function &F : FunctionList)
470 NumInstrs += F.getInstructionCount();
474 Comdat *Module::getOrInsertComdat(StringRef Name) {
475 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
476 Entry.second.Name = &Entry;
477 return &Entry.second;
480 PICLevel::Level Module::getPICLevel() const {
481 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
484 return PICLevel::NotPIC;
486 return static_cast<PICLevel::Level>(
487 cast<ConstantInt>(Val->getValue())->getZExtValue());
490 void Module::setPICLevel(PICLevel::Level PL) {
491 addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
494 PIELevel::Level Module::getPIELevel() const {
495 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
498 return PIELevel::Default;
500 return static_cast<PIELevel::Level>(
501 cast<ConstantInt>(Val->getValue())->getZExtValue());
504 void Module::setPIELevel(PIELevel::Level PL) {
505 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
508 void Module::setProfileSummary(Metadata *M) {
509 addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
512 Metadata *Module::getProfileSummary() {
513 return getModuleFlag("ProfileSummary");
516 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
517 OwnedMemoryBuffer = std::move(MB);
520 bool Module::getRtLibUseGOT() const {
521 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
522 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
525 void Module::setRtLibUseGOT() {
526 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
529 GlobalVariable *llvm::collectUsedGlobalVariables(
530 const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
531 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
532 GlobalVariable *GV = M.getGlobalVariable(Name);
533 if (!GV || !GV->hasInitializer())
536 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
537 for (Value *Op : Init->operands()) {
538 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());