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, FunctionType *Ty,
124 AttributeList AttributeList) {
125 // See if we have a definition for the specified function already.
126 GlobalValue *F = getNamedValue(Name);
129 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
130 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
131 New->setAttributes(AttributeList);
132 FunctionList.push_back(New);
133 return New; // Return the new prototype.
136 // If the function exists but has the wrong type, return a bitcast to the
138 if (F->getType() != PointerType::getUnqual(Ty))
139 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
141 // Otherwise, we just found the existing function or a prototype.
145 Constant *Module::getOrInsertFunction(StringRef Name,
147 return getOrInsertFunction(Name, Ty, AttributeList());
150 // getFunction - Look up the specified function in the module symbol table.
151 // If it does not exist, return null.
153 Function *Module::getFunction(StringRef Name) const {
154 return dyn_cast_or_null<Function>(getNamedValue(Name));
157 //===----------------------------------------------------------------------===//
158 // Methods for easy access to the global variables in the module.
161 /// getGlobalVariable - Look up the specified global variable in the module
162 /// symbol table. If it does not exist, return null. The type argument
163 /// should be the underlying type of the global, i.e., it should not have
164 /// the top-level PointerType, which represents the address of the global.
165 /// If AllowLocal is set to true, this function will return types that
166 /// have an local. By default, these types are not returned.
168 GlobalVariable *Module::getGlobalVariable(StringRef Name,
169 bool AllowLocal) const {
170 if (GlobalVariable *Result =
171 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
172 if (AllowLocal || !Result->hasLocalLinkage())
177 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
178 /// 1. If it does not exist, add a declaration of the global and return it.
179 /// 2. Else, the global exists but has the wrong type: return the function
180 /// with a constantexpr cast to the right type.
181 /// 3. Finally, if the existing global is the correct declaration, return the
183 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
184 // See if we have a definition for the specified global already.
185 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
188 GlobalVariable *New =
189 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
191 return New; // Return the new declaration.
194 // If the variable exists but has the wrong type, return a bitcast to the
196 Type *GVTy = GV->getType();
197 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
199 return ConstantExpr::getBitCast(GV, PTy);
201 // Otherwise, we just found the existing function or a prototype.
205 //===----------------------------------------------------------------------===//
206 // Methods for easy access to the global variables in the module.
209 // getNamedAlias - Look up the specified global in the module symbol table.
210 // If it does not exist, return null.
212 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
213 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
216 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
217 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
220 /// getNamedMetadata - Return the first NamedMDNode in the module with the
221 /// specified name. This method returns null if a NamedMDNode with the
222 /// specified name is not found.
223 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
224 SmallString<256> NameData;
225 StringRef NameRef = Name.toStringRef(NameData);
226 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
229 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
230 /// with the specified name. This method returns a new NamedMDNode if a
231 /// NamedMDNode with the specified name is not found.
232 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
234 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
236 NMD = new NamedMDNode(Name);
237 NMD->setParent(this);
238 NamedMDList.push_back(NMD);
243 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
245 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
246 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
247 NamedMDList.erase(NMD->getIterator());
250 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
251 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
252 uint64_t Val = Behavior->getLimitedValue();
253 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
254 MFB = static_cast<ModFlagBehavior>(Val);
261 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
263 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
264 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
265 if (!ModFlags) return;
267 for (const MDNode *Flag : ModFlags->operands()) {
269 if (Flag->getNumOperands() >= 3 &&
270 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
271 dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
272 // Check the operands of the MDNode before accessing the operands.
273 // The verifier will actually catch these failures.
274 MDString *Key = cast<MDString>(Flag->getOperand(1));
275 Metadata *Val = Flag->getOperand(2);
276 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
281 /// Return the corresponding value if Key appears in module flags, otherwise
283 Metadata *Module::getModuleFlag(StringRef Key) const {
284 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
285 getModuleFlagsMetadata(ModuleFlags);
286 for (const ModuleFlagEntry &MFE : ModuleFlags) {
287 if (Key == MFE.Key->getString())
293 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
294 /// represents module-level flags. This method returns null if there are no
295 /// module-level flags.
296 NamedMDNode *Module::getModuleFlagsMetadata() const {
297 return getNamedMetadata("llvm.module.flags");
300 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
301 /// represents module-level flags. If module-level flags aren't found, it
302 /// creates the named metadata that contains them.
303 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
304 return getOrInsertNamedMetadata("llvm.module.flags");
307 /// addModuleFlag - Add a module-level flag to the module-level flags
308 /// metadata. It will create the module-level flags named metadata if it doesn't
310 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
312 Type *Int32Ty = Type::getInt32Ty(Context);
314 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
315 MDString::get(Context, Key), Val};
316 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
318 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
320 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
322 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
324 Type *Int32Ty = Type::getInt32Ty(Context);
325 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
327 void Module::addModuleFlag(MDNode *Node) {
328 assert(Node->getNumOperands() == 3 &&
329 "Invalid number of operands for module flag!");
330 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
331 isa<MDString>(Node->getOperand(1)) &&
332 "Invalid operand types for module flag!");
333 getOrInsertModuleFlagsMetadata()->addOperand(Node);
336 void Module::setDataLayout(StringRef Desc) {
340 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
342 const DataLayout &Module::getDataLayout() const { return DL; }
344 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
345 return cast<DICompileUnit>(CUs->getOperand(Idx));
347 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
348 return cast<DICompileUnit>(CUs->getOperand(Idx));
351 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
352 while (CUs && (Idx < CUs->getNumOperands()) &&
353 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
357 //===----------------------------------------------------------------------===//
358 // Methods to control the materialization of GlobalValues in the Module.
360 void Module::setMaterializer(GVMaterializer *GVM) {
361 assert(!Materializer &&
362 "Module already has a GVMaterializer. Call materializeAll"
363 " to clear it out before setting another one.");
364 Materializer.reset(GVM);
367 Error Module::materialize(GlobalValue *GV) {
369 return Error::success();
371 return Materializer->materialize(GV);
374 Error Module::materializeAll() {
376 return Error::success();
377 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
378 return M->materializeModule();
381 Error Module::materializeMetadata() {
383 return Error::success();
384 return Materializer->materializeMetadata();
387 //===----------------------------------------------------------------------===//
388 // Other module related stuff.
391 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
392 // If we have a materializer, it is possible that some unread function
393 // uses a type that is currently not visible to a TypeFinder, so ask
394 // the materializer which types it created.
396 return Materializer->getIdentifiedStructTypes();
398 std::vector<StructType *> Ret;
399 TypeFinder SrcStructTypes;
400 SrcStructTypes.run(*this, true);
401 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
405 // dropAllReferences() - This function causes all the subelements to "let go"
406 // of all references that they are maintaining. This allows one to 'delete' a
407 // whole module at a time, even though there may be circular references... first
408 // all references are dropped, and all use counts go to zero. Then everything
409 // is deleted for real. Note that no operations are valid on an object that
410 // has "dropped all references", except operator delete.
412 void Module::dropAllReferences() {
413 for (Function &F : *this)
414 F.dropAllReferences();
416 for (GlobalVariable &GV : globals())
417 GV.dropAllReferences();
419 for (GlobalAlias &GA : aliases())
420 GA.dropAllReferences();
422 for (GlobalIFunc &GIF : ifuncs())
423 GIF.dropAllReferences();
426 unsigned Module::getNumberRegisterParameters() const {
428 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
431 return cast<ConstantInt>(Val->getValue())->getZExtValue();
434 unsigned Module::getDwarfVersion() const {
435 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
438 return cast<ConstantInt>(Val->getValue())->getZExtValue();
441 unsigned Module::getCodeViewFlag() const {
442 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
445 return cast<ConstantInt>(Val->getValue())->getZExtValue();
448 Comdat *Module::getOrInsertComdat(StringRef Name) {
449 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
450 Entry.second.Name = &Entry;
451 return &Entry.second;
454 PICLevel::Level Module::getPICLevel() const {
455 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
458 return PICLevel::NotPIC;
460 return static_cast<PICLevel::Level>(
461 cast<ConstantInt>(Val->getValue())->getZExtValue());
464 void Module::setPICLevel(PICLevel::Level PL) {
465 addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
468 PIELevel::Level Module::getPIELevel() const {
469 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
472 return PIELevel::Default;
474 return static_cast<PIELevel::Level>(
475 cast<ConstantInt>(Val->getValue())->getZExtValue());
478 void Module::setPIELevel(PIELevel::Level PL) {
479 addModuleFlag(ModFlagBehavior::Error, "PIE Level", PL);
482 void Module::setProfileSummary(Metadata *M) {
483 addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
486 Metadata *Module::getProfileSummary() {
487 return getModuleFlag("ProfileSummary");
490 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
491 OwnedMemoryBuffer = std::move(MB);
494 GlobalVariable *llvm::collectUsedGlobalVariables(
495 const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
496 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
497 GlobalVariable *GV = M.getGlobalVariable(Name);
498 if (!GV || !GV->hasInitializer())
501 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
502 for (Value *Op : Init->operands()) {
503 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());