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/Optional.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/Comdat.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GVMaterializer.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/SymbolTableListTraits.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/TypeFinder.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/IR/ValueSymbolTable.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/CodeGen.h"
45 #include "llvm/Support/Error.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/RandomNumberGenerator.h"
49 #include "llvm/Support/VersionTuple.h"
59 //===----------------------------------------------------------------------===//
60 // Methods to implement the globals and functions lists.
63 // Explicit instantiations of SymbolTableListTraits since some of the methods
64 // are not in the public header file.
65 template class llvm::SymbolTableListTraits<Function>;
66 template class llvm::SymbolTableListTraits<GlobalVariable>;
67 template class llvm::SymbolTableListTraits<GlobalAlias>;
68 template class llvm::SymbolTableListTraits<GlobalIFunc>;
70 //===----------------------------------------------------------------------===//
71 // Primitive Module methods.
74 Module::Module(StringRef MID, LLVMContext &C)
75 : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
76 ValSymTab = new ValueSymbolTable();
77 NamedMDSymTab = new StringMap<NamedMDNode *>();
78 Context.addModule(this);
82 Context.removeModule(this);
90 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
93 std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
94 SmallString<32> Salt(P->getPassName());
96 // This RNG is guaranteed to produce the same random stream only
97 // when the Module ID and thus the input filename is the same. This
98 // might be problematic if the input filename extension changes
99 // (e.g. from .c to .bc or .ll).
101 // We could store this salt in NamedMetadata, but this would make
102 // the parameter non-const. This would unfortunately make this
103 // interface unusable by any Machine passes, since they only have a
104 // const reference to their IR Module. Alternatively we can always
105 // store salt metadata from the Module constructor.
106 Salt += sys::path::filename(getModuleIdentifier());
108 return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt));
111 /// getNamedValue - Return the first global value in the module with
112 /// the specified name, of arbitrary type. This method returns null
113 /// if a global with the specified name is not found.
114 GlobalValue *Module::getNamedValue(StringRef Name) const {
115 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
118 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
119 /// This ID is uniqued across modules in the current LLVMContext.
120 unsigned Module::getMDKindID(StringRef Name) const {
121 return Context.getMDKindID(Name);
124 /// getMDKindNames - Populate client supplied SmallVector with the name for
125 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
126 /// so it is filled in as an empty string.
127 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
128 return Context.getMDKindNames(Result);
131 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
132 return Context.getOperandBundleTags(Result);
135 //===----------------------------------------------------------------------===//
136 // Methods for easy access to the functions in the module.
139 // getOrInsertFunction - Look up the specified function in the module symbol
140 // table. If it does not exist, add a prototype for the function and return
141 // it. This is nice because it allows most passes to get away with not handling
142 // the symbol table directly for this common task.
144 Constant *Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
145 AttributeList AttributeList) {
146 // See if we have a definition for the specified function already.
147 GlobalValue *F = getNamedValue(Name);
150 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
151 DL.getProgramAddressSpace(), Name);
152 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
153 New->setAttributes(AttributeList);
154 FunctionList.push_back(New);
155 return New; // Return the new prototype.
158 // If the function exists but has the wrong type, return a bitcast to the
160 auto *PTy = PointerType::get(Ty, F->getAddressSpace());
161 if (F->getType() != PTy)
162 return ConstantExpr::getBitCast(F, PTy);
164 // Otherwise, we just found the existing function or a prototype.
168 Constant *Module::getOrInsertFunction(StringRef Name,
170 return getOrInsertFunction(Name, Ty, AttributeList());
173 // getFunction - Look up the specified function in the module symbol table.
174 // If it does not exist, return null.
176 Function *Module::getFunction(StringRef Name) const {
177 return dyn_cast_or_null<Function>(getNamedValue(Name));
180 //===----------------------------------------------------------------------===//
181 // Methods for easy access to the global variables in the module.
184 /// getGlobalVariable - Look up the specified global variable in the module
185 /// symbol table. If it does not exist, return null. The type argument
186 /// should be the underlying type of the global, i.e., it should not have
187 /// the top-level PointerType, which represents the address of the global.
188 /// If AllowLocal is set to true, this function will return types that
189 /// have an local. By default, these types are not returned.
191 GlobalVariable *Module::getGlobalVariable(StringRef Name,
192 bool AllowLocal) const {
193 if (GlobalVariable *Result =
194 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
195 if (AllowLocal || !Result->hasLocalLinkage())
200 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
201 /// 1. If it does not exist, add a declaration of the global and return it.
202 /// 2. Else, the global exists but has the wrong type: return the function
203 /// with a constantexpr cast to the right type.
204 /// 3. Finally, if the existing global is the correct declaration, return the
206 Constant *Module::getOrInsertGlobal(
207 StringRef Name, Type *Ty,
208 function_ref<GlobalVariable *()> CreateGlobalCallback) {
209 // See if we have a definition for the specified global already.
210 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
212 GV = CreateGlobalCallback();
213 assert(GV && "The CreateGlobalCallback is expected to create a global");
215 // If the variable exists but has the wrong type, return a bitcast to the
217 Type *GVTy = GV->getType();
218 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
220 return ConstantExpr::getBitCast(GV, PTy);
222 // Otherwise, we just found the existing function or a prototype.
226 // Overload to construct a global variable using its constructor's defaults.
227 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
228 return getOrInsertGlobal(Name, Ty, [&] {
229 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
234 //===----------------------------------------------------------------------===//
235 // Methods for easy access to the global variables in the module.
238 // getNamedAlias - Look up the specified global in the module symbol table.
239 // If it does not exist, return null.
241 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
242 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
245 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
246 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
249 /// getNamedMetadata - Return the first NamedMDNode in the module with the
250 /// specified name. This method returns null if a NamedMDNode with the
251 /// specified name is not found.
252 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
253 SmallString<256> NameData;
254 StringRef NameRef = Name.toStringRef(NameData);
255 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
258 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
259 /// with the specified name. This method returns a new NamedMDNode if a
260 /// NamedMDNode with the specified name is not found.
261 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
263 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
265 NMD = new NamedMDNode(Name);
266 NMD->setParent(this);
267 NamedMDList.push_back(NMD);
272 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
274 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
275 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
276 NamedMDList.erase(NMD->getIterator());
279 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
280 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
281 uint64_t Val = Behavior->getLimitedValue();
282 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
283 MFB = static_cast<ModFlagBehavior>(Val);
290 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
292 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
293 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
294 if (!ModFlags) return;
296 for (const MDNode *Flag : ModFlags->operands()) {
298 if (Flag->getNumOperands() >= 3 &&
299 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
300 dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
301 // Check the operands of the MDNode before accessing the operands.
302 // The verifier will actually catch these failures.
303 MDString *Key = cast<MDString>(Flag->getOperand(1));
304 Metadata *Val = Flag->getOperand(2);
305 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
310 /// Return the corresponding value if Key appears in module flags, otherwise
312 Metadata *Module::getModuleFlag(StringRef Key) const {
313 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
314 getModuleFlagsMetadata(ModuleFlags);
315 for (const ModuleFlagEntry &MFE : ModuleFlags) {
316 if (Key == MFE.Key->getString())
322 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
323 /// represents module-level flags. This method returns null if there are no
324 /// module-level flags.
325 NamedMDNode *Module::getModuleFlagsMetadata() const {
326 return getNamedMetadata("llvm.module.flags");
329 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
330 /// represents module-level flags. If module-level flags aren't found, it
331 /// creates the named metadata that contains them.
332 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
333 return getOrInsertNamedMetadata("llvm.module.flags");
336 /// addModuleFlag - Add a module-level flag to the module-level flags
337 /// metadata. It will create the module-level flags named metadata if it doesn't
339 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
341 Type *Int32Ty = Type::getInt32Ty(Context);
343 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
344 MDString::get(Context, Key), Val};
345 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
347 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
349 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
351 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
353 Type *Int32Ty = Type::getInt32Ty(Context);
354 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
356 void Module::addModuleFlag(MDNode *Node) {
357 assert(Node->getNumOperands() == 3 &&
358 "Invalid number of operands for module flag!");
359 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
360 isa<MDString>(Node->getOperand(1)) &&
361 "Invalid operand types for module flag!");
362 getOrInsertModuleFlagsMetadata()->addOperand(Node);
365 void Module::setDataLayout(StringRef Desc) {
369 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
371 const DataLayout &Module::getDataLayout() const { return DL; }
373 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
374 return cast<DICompileUnit>(CUs->getOperand(Idx));
376 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
377 return cast<DICompileUnit>(CUs->getOperand(Idx));
380 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
381 while (CUs && (Idx < CUs->getNumOperands()) &&
382 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
386 //===----------------------------------------------------------------------===//
387 // Methods to control the materialization of GlobalValues in the Module.
389 void Module::setMaterializer(GVMaterializer *GVM) {
390 assert(!Materializer &&
391 "Module already has a GVMaterializer. Call materializeAll"
392 " to clear it out before setting another one.");
393 Materializer.reset(GVM);
396 Error Module::materialize(GlobalValue *GV) {
398 return Error::success();
400 return Materializer->materialize(GV);
403 Error Module::materializeAll() {
405 return Error::success();
406 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
407 return M->materializeModule();
410 Error Module::materializeMetadata() {
412 return Error::success();
413 return Materializer->materializeMetadata();
416 //===----------------------------------------------------------------------===//
417 // Other module related stuff.
420 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
421 // If we have a materializer, it is possible that some unread function
422 // uses a type that is currently not visible to a TypeFinder, so ask
423 // the materializer which types it created.
425 return Materializer->getIdentifiedStructTypes();
427 std::vector<StructType *> Ret;
428 TypeFinder SrcStructTypes;
429 SrcStructTypes.run(*this, true);
430 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
434 // dropAllReferences() - This function causes all the subelements to "let go"
435 // of all references that they are maintaining. This allows one to 'delete' a
436 // whole module at a time, even though there may be circular references... first
437 // all references are dropped, and all use counts go to zero. Then everything
438 // is deleted for real. Note that no operations are valid on an object that
439 // has "dropped all references", except operator delete.
441 void Module::dropAllReferences() {
442 for (Function &F : *this)
443 F.dropAllReferences();
445 for (GlobalVariable &GV : globals())
446 GV.dropAllReferences();
448 for (GlobalAlias &GA : aliases())
449 GA.dropAllReferences();
451 for (GlobalIFunc &GIF : ifuncs())
452 GIF.dropAllReferences();
455 unsigned Module::getNumberRegisterParameters() const {
457 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
460 return cast<ConstantInt>(Val->getValue())->getZExtValue();
463 unsigned Module::getDwarfVersion() const {
464 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
467 return cast<ConstantInt>(Val->getValue())->getZExtValue();
470 unsigned Module::getCodeViewFlag() const {
471 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
474 return cast<ConstantInt>(Val->getValue())->getZExtValue();
477 unsigned Module::getInstructionCount() {
478 unsigned NumInstrs = 0;
479 for (Function &F : FunctionList)
480 NumInstrs += F.getInstructionCount();
484 Comdat *Module::getOrInsertComdat(StringRef Name) {
485 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
486 Entry.second.Name = &Entry;
487 return &Entry.second;
490 PICLevel::Level Module::getPICLevel() const {
491 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
494 return PICLevel::NotPIC;
496 return static_cast<PICLevel::Level>(
497 cast<ConstantInt>(Val->getValue())->getZExtValue());
500 void Module::setPICLevel(PICLevel::Level PL) {
501 addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
504 PIELevel::Level Module::getPIELevel() const {
505 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
508 return PIELevel::Default;
510 return static_cast<PIELevel::Level>(
511 cast<ConstantInt>(Val->getValue())->getZExtValue());
514 void Module::setPIELevel(PIELevel::Level PL) {
515 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
518 Optional<CodeModel::Model> Module::getCodeModel() const {
519 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
524 return static_cast<CodeModel::Model>(
525 cast<ConstantInt>(Val->getValue())->getZExtValue());
528 void Module::setCodeModel(CodeModel::Model CL) {
529 // Linking object files with different code models is undefined behavior
530 // because the compiler would have to generate additional code (to span
531 // longer jumps) if a larger code model is used with a smaller one.
532 // Therefore we will treat attempts to mix code models as an error.
533 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
536 void Module::setProfileSummary(Metadata *M) {
537 addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
540 Metadata *Module::getProfileSummary() {
541 return getModuleFlag("ProfileSummary");
544 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
545 OwnedMemoryBuffer = std::move(MB);
548 bool Module::getRtLibUseGOT() const {
549 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
550 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
553 void Module::setRtLibUseGOT() {
554 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
557 void Module::setSDKVersion(const VersionTuple &V) {
558 SmallVector<unsigned, 3> Entries;
559 Entries.push_back(V.getMajor());
560 if (auto Minor = V.getMinor()) {
561 Entries.push_back(*Minor);
562 if (auto Subminor = V.getSubminor())
563 Entries.push_back(*Subminor);
564 // Ignore the 'build' component as it can't be represented in the object
567 addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
568 ConstantDataArray::get(Context, Entries));
571 VersionTuple Module::getSDKVersion() const {
572 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
575 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
578 auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
579 if (Index >= Arr->getNumElements())
581 return (unsigned)Arr->getElementAsInteger(Index);
583 auto Major = getVersionComponent(0);
586 VersionTuple Result = VersionTuple(*Major);
587 if (auto Minor = getVersionComponent(1)) {
588 Result = VersionTuple(*Major, *Minor);
589 if (auto Subminor = getVersionComponent(2)) {
590 Result = VersionTuple(*Major, *Minor, *Subminor);
596 GlobalVariable *llvm::collectUsedGlobalVariables(
597 const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
598 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
599 GlobalVariable *GV = M.getGlobalVariable(Name);
600 if (!GV || !GV->hasInitializer())
603 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
604 for (Value *Op : Init->operands()) {
605 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());