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/IR/TypeFinder.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/RandomNumberGenerator.h"
35 //===----------------------------------------------------------------------===//
36 // Methods to implement the globals and functions lists.
39 // Explicit instantiations of SymbolTableListTraits since some of the methods
40 // are not in the public header file.
41 template class llvm::SymbolTableListTraits<Function, Module>;
42 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
43 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
45 //===----------------------------------------------------------------------===//
46 // Primitive Module methods.
49 Module::Module(StringRef MID, LLVMContext &C)
50 : Context(C), Materializer(), ModuleID(MID), RNG(nullptr), DL("") {
51 ValSymTab = new ValueSymbolTable();
52 NamedMDSymTab = new StringMap<NamedMDNode *>();
53 Context.addModule(this);
57 Context.removeModule(this);
64 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
68 /// getNamedValue - Return the first global value in the module with
69 /// the specified name, of arbitrary type. This method returns null
70 /// if a global with the specified name is not found.
71 GlobalValue *Module::getNamedValue(StringRef Name) const {
72 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
75 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
76 /// This ID is uniqued across modules in the current LLVMContext.
77 unsigned Module::getMDKindID(StringRef Name) const {
78 return Context.getMDKindID(Name);
81 /// getMDKindNames - Populate client supplied SmallVector with the name for
82 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
83 /// so it is filled in as an empty string.
84 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
85 return Context.getMDKindNames(Result);
89 //===----------------------------------------------------------------------===//
90 // Methods for easy access to the functions in the module.
93 // getOrInsertFunction - Look up the specified function in the module symbol
94 // table. If it does not exist, add a prototype for the function and return
95 // it. This is nice because it allows most passes to get away with not handling
96 // the symbol table directly for this common task.
98 Constant *Module::getOrInsertFunction(StringRef Name,
100 AttributeSet AttributeList) {
101 // See if we have a definition for the specified function already.
102 GlobalValue *F = getNamedValue(Name);
105 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
106 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
107 New->setAttributes(AttributeList);
108 FunctionList.push_back(New);
109 return New; // Return the new prototype.
112 // If the function exists but has the wrong type, return a bitcast to the
114 if (F->getType() != PointerType::getUnqual(Ty))
115 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
117 // Otherwise, we just found the existing function or a prototype.
121 Constant *Module::getOrInsertFunction(StringRef Name,
123 return getOrInsertFunction(Name, Ty, AttributeSet());
126 // getOrInsertFunction - Look up the specified function in the module symbol
127 // table. If it does not exist, add a prototype for the function and return it.
128 // This version of the method takes a null terminated list of function
129 // arguments, which makes it easier for clients to use.
131 Constant *Module::getOrInsertFunction(StringRef Name,
132 AttributeSet AttributeList,
135 va_start(Args, RetTy);
137 // Build the list of argument types...
138 std::vector<Type*> ArgTys;
139 while (Type *ArgTy = va_arg(Args, Type*))
140 ArgTys.push_back(ArgTy);
144 // Build the function type and chain to the other getOrInsertFunction...
145 return getOrInsertFunction(Name,
146 FunctionType::get(RetTy, ArgTys, false),
150 Constant *Module::getOrInsertFunction(StringRef Name,
153 va_start(Args, RetTy);
155 // Build the list of argument types...
156 std::vector<Type*> ArgTys;
157 while (Type *ArgTy = va_arg(Args, Type*))
158 ArgTys.push_back(ArgTy);
162 // Build the function type and chain to the other getOrInsertFunction...
163 return getOrInsertFunction(Name,
164 FunctionType::get(RetTy, ArgTys, false),
168 // getFunction - Look up the specified function in the module symbol table.
169 // If it does not exist, return null.
171 Function *Module::getFunction(StringRef Name) const {
172 return dyn_cast_or_null<Function>(getNamedValue(Name));
175 //===----------------------------------------------------------------------===//
176 // Methods for easy access to the global variables in the module.
179 /// getGlobalVariable - Look up the specified global variable in the module
180 /// symbol table. If it does not exist, return null. The type argument
181 /// should be the underlying type of the global, i.e., it should not have
182 /// the top-level PointerType, which represents the address of the global.
183 /// If AllowLocal is set to true, this function will return types that
184 /// have an local. By default, these types are not returned.
186 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
187 if (GlobalVariable *Result =
188 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
189 if (AllowLocal || !Result->hasLocalLinkage())
194 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
195 /// 1. If it does not exist, add a declaration of the global and return it.
196 /// 2. Else, the global exists but has the wrong type: return the function
197 /// with a constantexpr cast to the right type.
198 /// 3. Finally, if the existing global is the correct declaration, return the
200 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
201 // See if we have a definition for the specified global already.
202 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
205 GlobalVariable *New =
206 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
208 return New; // Return the new declaration.
211 // If the variable exists but has the wrong type, return a bitcast to the
213 Type *GVTy = GV->getType();
214 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
216 return ConstantExpr::getBitCast(GV, PTy);
218 // Otherwise, we just found the existing function or a prototype.
222 //===----------------------------------------------------------------------===//
223 // Methods for easy access to the global variables in the module.
226 // getNamedAlias - Look up the specified global in the module symbol table.
227 // If it does not exist, return null.
229 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
230 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
233 /// getNamedMetadata - Return the first NamedMDNode in the module with the
234 /// specified name. This method returns null if a NamedMDNode with the
235 /// specified name is not found.
236 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
237 SmallString<256> NameData;
238 StringRef NameRef = Name.toStringRef(NameData);
239 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
242 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
243 /// with the specified name. This method returns a new NamedMDNode if a
244 /// NamedMDNode with the specified name is not found.
245 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
247 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
249 NMD = new NamedMDNode(Name);
250 NMD->setParent(this);
251 NamedMDList.push_back(NMD);
256 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
258 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
259 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
260 NamedMDList.erase(NMD);
263 bool Module::isValidModFlagBehavior(Value *V, ModFlagBehavior &MFB) {
264 if (ConstantInt *Behavior = dyn_cast<ConstantInt>(V)) {
265 uint64_t Val = Behavior->getLimitedValue();
266 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
267 MFB = static_cast<ModFlagBehavior>(Val);
274 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
276 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
277 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
278 if (!ModFlags) return;
280 for (const MDNode *Flag : ModFlags->operands()) {
282 if (Flag->getNumOperands() >= 3 &&
283 isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
284 isa<MDString>(Flag->getOperand(1))) {
285 // Check the operands of the MDNode before accessing the operands.
286 // The verifier will actually catch these failures.
287 MDString *Key = cast<MDString>(Flag->getOperand(1));
288 Value *Val = Flag->getOperand(2);
289 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
294 /// Return the corresponding value if Key appears in module flags, otherwise
296 Value *Module::getModuleFlag(StringRef Key) const {
297 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
298 getModuleFlagsMetadata(ModuleFlags);
299 for (const ModuleFlagEntry &MFE : ModuleFlags) {
300 if (Key == MFE.Key->getString())
306 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
307 /// represents module-level flags. This method returns null if there are no
308 /// module-level flags.
309 NamedMDNode *Module::getModuleFlagsMetadata() const {
310 return getNamedMetadata("llvm.module.flags");
313 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
314 /// represents module-level flags. If module-level flags aren't found, it
315 /// creates the named metadata that contains them.
316 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
317 return getOrInsertNamedMetadata("llvm.module.flags");
320 /// addModuleFlag - Add a module-level flag to the module-level flags
321 /// metadata. It will create the module-level flags named metadata if it doesn't
323 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
325 Type *Int32Ty = Type::getInt32Ty(Context);
327 ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
329 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
331 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
333 Type *Int32Ty = Type::getInt32Ty(Context);
334 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
336 void Module::addModuleFlag(MDNode *Node) {
337 assert(Node->getNumOperands() == 3 &&
338 "Invalid number of operands for module flag!");
339 assert(isa<ConstantInt>(Node->getOperand(0)) &&
340 isa<MDString>(Node->getOperand(1)) &&
341 "Invalid operand types for module flag!");
342 getOrInsertModuleFlagsMetadata()->addOperand(Node);
345 void Module::setDataLayout(StringRef Desc) {
351 DataLayoutStr = DL.getStringRepresentation();
352 // DataLayoutStr is now equivalent to Desc, but since the representation
353 // is not unique, they may not be identical.
357 void Module::setDataLayout(const DataLayout *Other) {
363 DataLayoutStr = DL.getStringRepresentation();
367 const DataLayout *Module::getDataLayout() const {
368 if (DataLayoutStr.empty())
373 // We want reproducible builds, but ModuleID may be a full path so we just use
374 // the filename to salt the RNG (although it is not guaranteed to be unique).
375 RandomNumberGenerator &Module::getRNG() const {
376 if (RNG == nullptr) {
377 StringRef Salt = sys::path::filename(ModuleID);
378 RNG = new RandomNumberGenerator(Salt);
383 //===----------------------------------------------------------------------===//
384 // Methods to control the materialization of GlobalValues in the Module.
386 void Module::setMaterializer(GVMaterializer *GVM) {
387 assert(!Materializer &&
388 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
389 " to clear it out before setting another one.");
390 Materializer.reset(GVM);
393 bool Module::isDematerializable(const GlobalValue *GV) const {
395 return Materializer->isDematerializable(GV);
399 std::error_code Module::materialize(GlobalValue *GV) {
401 return std::error_code();
403 return Materializer->materialize(GV);
406 void Module::Dematerialize(GlobalValue *GV) {
408 return Materializer->Dematerialize(GV);
411 std::error_code Module::materializeAll() {
413 return std::error_code();
414 return Materializer->MaterializeModule(this);
417 std::error_code Module::materializeAllPermanently() {
418 if (std::error_code EC = materializeAll())
421 Materializer.reset();
422 return std::error_code();
425 //===----------------------------------------------------------------------===//
426 // Other module related stuff.
429 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
430 // If we have a materializer, it is possible that some unread function
431 // uses a type that is currently not visible to a TypeFinder, so ask
432 // the materializer which types it created.
434 return Materializer->getIdentifiedStructTypes();
436 std::vector<StructType *> Ret;
437 TypeFinder SrcStructTypes;
438 SrcStructTypes.run(*this, true);
439 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
443 // dropAllReferences() - This function causes all the subelements to "let go"
444 // of all references that they are maintaining. This allows one to 'delete' a
445 // whole module at a time, even though there may be circular references... first
446 // all references are dropped, and all use counts go to zero. Then everything
447 // is deleted for real. Note that no operations are valid on an object that
448 // has "dropped all references", except operator delete.
450 void Module::dropAllReferences() {
451 for (Function &F : *this)
452 F.dropAllReferences();
454 for (GlobalVariable &GV : globals())
455 GV.dropAllReferences();
457 for (GlobalAlias &GA : aliases())
458 GA.dropAllReferences();
461 unsigned Module::getDwarfVersion() const {
462 Value *Val = getModuleFlag("Dwarf Version");
464 return dwarf::DWARF_VERSION;
465 return cast<ConstantInt>(Val)->getZExtValue();
468 Comdat *Module::getOrInsertComdat(StringRef Name) {
469 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
470 Entry.second.Name = &Entry;
471 return &Entry.second;
474 PICLevel::Level Module::getPICLevel() const {
475 Value *Val = getModuleFlag("PIC Level");
478 return PICLevel::Default;
480 return static_cast<PICLevel::Level>(cast<ConstantInt>(Val)->getZExtValue());
483 void Module::setPICLevel(PICLevel::Level PL) {
484 addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);