xref: /freebsd-12.1/contrib/llvm/lib/IR/Module.cpp (revision b5893f02)
15517e702SDimitry Andric //===- Module.cpp - Implement the Module class ----------------------------===//
2139f7f9bSDimitry Andric //
3139f7f9bSDimitry Andric //                     The LLVM Compiler Infrastructure
4139f7f9bSDimitry Andric //
5139f7f9bSDimitry Andric // This file is distributed under the University of Illinois Open Source
6139f7f9bSDimitry Andric // License. See LICENSE.TXT for details.
7139f7f9bSDimitry Andric //
8139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
9139f7f9bSDimitry Andric //
10139f7f9bSDimitry Andric // This file implements the Module class for the IR library.
11139f7f9bSDimitry Andric //
12139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
13139f7f9bSDimitry Andric 
14db17bf38SDimitry Andric #include "llvm/IR/Module.h"
15139f7f9bSDimitry Andric #include "SymbolTableListTraitsImpl.h"
16*b5893f02SDimitry Andric #include "llvm/ADT/Optional.h"
173ca95b02SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
18139f7f9bSDimitry Andric #include "llvm/ADT/SmallString.h"
195517e702SDimitry Andric #include "llvm/ADT/SmallVector.h"
205517e702SDimitry Andric #include "llvm/ADT/StringMap.h"
215517e702SDimitry Andric #include "llvm/ADT/StringRef.h"
225517e702SDimitry Andric #include "llvm/ADT/Twine.h"
235517e702SDimitry Andric #include "llvm/IR/Attributes.h"
245517e702SDimitry Andric #include "llvm/IR/Comdat.h"
25139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
265517e702SDimitry Andric #include "llvm/IR/DataLayout.h"
273ca95b02SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
28db17bf38SDimitry Andric #include "llvm/IR/DerivedTypes.h"
295517e702SDimitry Andric #include "llvm/IR/Function.h"
30db17bf38SDimitry Andric #include "llvm/IR/GVMaterializer.h"
315517e702SDimitry Andric #include "llvm/IR/GlobalAlias.h"
325517e702SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
335517e702SDimitry Andric #include "llvm/IR/GlobalValue.h"
345517e702SDimitry Andric #include "llvm/IR/GlobalVariable.h"
35139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
365517e702SDimitry Andric #include "llvm/IR/Metadata.h"
375517e702SDimitry Andric #include "llvm/IR/SymbolTableListTraits.h"
385517e702SDimitry Andric #include "llvm/IR/Type.h"
3939d628a0SDimitry Andric #include "llvm/IR/TypeFinder.h"
405517e702SDimitry Andric #include "llvm/IR/Value.h"
415517e702SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
425517e702SDimitry Andric #include "llvm/Pass.h"
435517e702SDimitry Andric #include "llvm/Support/Casting.h"
445517e702SDimitry Andric #include "llvm/Support/CodeGen.h"
45d88c1a5aSDimitry Andric #include "llvm/Support/Error.h"
46d88c1a5aSDimitry Andric #include "llvm/Support/MemoryBuffer.h"
4791bc56edSDimitry Andric #include "llvm/Support/Path.h"
4891bc56edSDimitry Andric #include "llvm/Support/RandomNumberGenerator.h"
49*b5893f02SDimitry Andric #include "llvm/Support/VersionTuple.h"
50139f7f9bSDimitry Andric #include <algorithm>
515517e702SDimitry Andric #include <cassert>
525517e702SDimitry Andric #include <cstdint>
535517e702SDimitry Andric #include <memory>
545517e702SDimitry Andric #include <utility>
555517e702SDimitry Andric #include <vector>
567d523365SDimitry Andric 
57139f7f9bSDimitry Andric using namespace llvm;
58139f7f9bSDimitry Andric 
59139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
60139f7f9bSDimitry Andric // Methods to implement the globals and functions lists.
61139f7f9bSDimitry Andric //
62139f7f9bSDimitry Andric 
63139f7f9bSDimitry Andric // Explicit instantiations of SymbolTableListTraits since some of the methods
64139f7f9bSDimitry Andric // are not in the public header file.
657d523365SDimitry Andric template class llvm::SymbolTableListTraits<Function>;
667d523365SDimitry Andric template class llvm::SymbolTableListTraits<GlobalVariable>;
677d523365SDimitry Andric template class llvm::SymbolTableListTraits<GlobalAlias>;
683ca95b02SDimitry Andric template class llvm::SymbolTableListTraits<GlobalIFunc>;
69139f7f9bSDimitry Andric 
70139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
71139f7f9bSDimitry Andric // Primitive Module methods.
72139f7f9bSDimitry Andric //
73139f7f9bSDimitry Andric 
Module(StringRef MID,LLVMContext & C)74139f7f9bSDimitry Andric Module::Module(StringRef MID, LLVMContext &C)
753ca95b02SDimitry Andric     : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
76139f7f9bSDimitry Andric   ValSymTab = new ValueSymbolTable();
77139f7f9bSDimitry Andric   NamedMDSymTab = new StringMap<NamedMDNode *>();
78139f7f9bSDimitry Andric   Context.addModule(this);
79139f7f9bSDimitry Andric }
80139f7f9bSDimitry Andric 
~Module()81139f7f9bSDimitry Andric Module::~Module() {
82139f7f9bSDimitry Andric   Context.removeModule(this);
83139f7f9bSDimitry Andric   dropAllReferences();
84139f7f9bSDimitry Andric   GlobalList.clear();
85139f7f9bSDimitry Andric   FunctionList.clear();
86139f7f9bSDimitry Andric   AliasList.clear();
873ca95b02SDimitry Andric   IFuncList.clear();
88139f7f9bSDimitry Andric   NamedMDList.clear();
89139f7f9bSDimitry Andric   delete ValSymTab;
90139f7f9bSDimitry Andric   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
91139f7f9bSDimitry Andric }
92139f7f9bSDimitry Andric 
createRNG(const Pass * P) const93c4394386SDimitry Andric std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
9439d628a0SDimitry Andric   SmallString<32> Salt(P->getPassName());
9539d628a0SDimitry Andric 
9639d628a0SDimitry Andric   // This RNG is guaranteed to produce the same random stream only
9739d628a0SDimitry Andric   // when the Module ID and thus the input filename is the same. This
9839d628a0SDimitry Andric   // might be problematic if the input filename extension changes
9939d628a0SDimitry Andric   // (e.g. from .c to .bc or .ll).
10039d628a0SDimitry Andric   //
10139d628a0SDimitry Andric   // We could store this salt in NamedMetadata, but this would make
10239d628a0SDimitry Andric   // the parameter non-const. This would unfortunately make this
10339d628a0SDimitry Andric   // interface unusable by any Machine passes, since they only have a
10439d628a0SDimitry Andric   // const reference to their IR Module. Alternatively we can always
10539d628a0SDimitry Andric   // store salt metadata from the Module constructor.
10639d628a0SDimitry Andric   Salt += sys::path::filename(getModuleIdentifier());
10739d628a0SDimitry Andric 
108b40b48b8SDimitry Andric   return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt));
10939d628a0SDimitry Andric }
11039d628a0SDimitry Andric 
111139f7f9bSDimitry Andric /// getNamedValue - Return the first global value in the module with
112139f7f9bSDimitry Andric /// the specified name, of arbitrary type.  This method returns null
113139f7f9bSDimitry Andric /// if a global with the specified name is not found.
getNamedValue(StringRef Name) const114139f7f9bSDimitry Andric GlobalValue *Module::getNamedValue(StringRef Name) const {
115139f7f9bSDimitry Andric   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
116139f7f9bSDimitry Andric }
117139f7f9bSDimitry Andric 
118139f7f9bSDimitry Andric /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
119139f7f9bSDimitry Andric /// This ID is uniqued across modules in the current LLVMContext.
getMDKindID(StringRef Name) const120139f7f9bSDimitry Andric unsigned Module::getMDKindID(StringRef Name) const {
121139f7f9bSDimitry Andric   return Context.getMDKindID(Name);
122139f7f9bSDimitry Andric }
123139f7f9bSDimitry Andric 
124139f7f9bSDimitry Andric /// getMDKindNames - Populate client supplied SmallVector with the name for
125139f7f9bSDimitry Andric /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
126139f7f9bSDimitry Andric /// so it is filled in as an empty string.
getMDKindNames(SmallVectorImpl<StringRef> & Result) const127139f7f9bSDimitry Andric void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
128139f7f9bSDimitry Andric   return Context.getMDKindNames(Result);
129139f7f9bSDimitry Andric }
130139f7f9bSDimitry Andric 
getOperandBundleTags(SmallVectorImpl<StringRef> & Result) const1317d523365SDimitry Andric void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
1327d523365SDimitry Andric   return Context.getOperandBundleTags(Result);
1337d523365SDimitry Andric }
134139f7f9bSDimitry Andric 
135139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
136139f7f9bSDimitry Andric // Methods for easy access to the functions in the module.
137139f7f9bSDimitry Andric //
138139f7f9bSDimitry Andric 
139139f7f9bSDimitry Andric // getOrInsertFunction - Look up the specified function in the module symbol
140139f7f9bSDimitry Andric // table.  If it does not exist, add a prototype for the function and return
141139f7f9bSDimitry Andric // it.  This is nice because it allows most passes to get away with not handling
142139f7f9bSDimitry Andric // the symbol table directly for this common task.
143139f7f9bSDimitry Andric //
getOrInsertFunction(StringRef Name,FunctionType * Ty,AttributeList AttributeList)1447a7e6055SDimitry Andric Constant *Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
1457a7e6055SDimitry Andric                                       AttributeList AttributeList) {
146139f7f9bSDimitry Andric   // See if we have a definition for the specified function already.
147139f7f9bSDimitry Andric   GlobalValue *F = getNamedValue(Name);
14891bc56edSDimitry Andric   if (!F) {
149139f7f9bSDimitry Andric     // Nope, add it
150*b5893f02SDimitry Andric     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
151*b5893f02SDimitry Andric                                      DL.getProgramAddressSpace(), Name);
152139f7f9bSDimitry Andric     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
153139f7f9bSDimitry Andric       New->setAttributes(AttributeList);
154139f7f9bSDimitry Andric     FunctionList.push_back(New);
155139f7f9bSDimitry Andric     return New;                    // Return the new prototype.
156139f7f9bSDimitry Andric   }
157139f7f9bSDimitry Andric 
158139f7f9bSDimitry Andric   // If the function exists but has the wrong type, return a bitcast to the
159139f7f9bSDimitry Andric   // right type.
160*b5893f02SDimitry Andric   auto *PTy = PointerType::get(Ty, F->getAddressSpace());
161*b5893f02SDimitry Andric   if (F->getType() != PTy)
162*b5893f02SDimitry Andric     return ConstantExpr::getBitCast(F, PTy);
163139f7f9bSDimitry Andric 
164139f7f9bSDimitry Andric   // Otherwise, we just found the existing function or a prototype.
165139f7f9bSDimitry Andric   return F;
166139f7f9bSDimitry Andric }
167139f7f9bSDimitry Andric 
getOrInsertFunction(StringRef Name,FunctionType * Ty)168139f7f9bSDimitry Andric Constant *Module::getOrInsertFunction(StringRef Name,
169139f7f9bSDimitry Andric                                       FunctionType *Ty) {
1707a7e6055SDimitry Andric   return getOrInsertFunction(Name, Ty, AttributeList());
171139f7f9bSDimitry Andric }
172139f7f9bSDimitry Andric 
173139f7f9bSDimitry Andric // getFunction - Look up the specified function in the module symbol table.
174139f7f9bSDimitry Andric // If it does not exist, return null.
175139f7f9bSDimitry Andric //
getFunction(StringRef Name) const176139f7f9bSDimitry Andric Function *Module::getFunction(StringRef Name) const {
177139f7f9bSDimitry Andric   return dyn_cast_or_null<Function>(getNamedValue(Name));
178139f7f9bSDimitry Andric }
179139f7f9bSDimitry Andric 
180139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
181139f7f9bSDimitry Andric // Methods for easy access to the global variables in the module.
182139f7f9bSDimitry Andric //
183139f7f9bSDimitry Andric 
184139f7f9bSDimitry Andric /// getGlobalVariable - Look up the specified global variable in the module
185139f7f9bSDimitry Andric /// symbol table.  If it does not exist, return null.  The type argument
186139f7f9bSDimitry Andric /// should be the underlying type of the global, i.e., it should not have
187139f7f9bSDimitry Andric /// the top-level PointerType, which represents the address of the global.
188139f7f9bSDimitry Andric /// If AllowLocal is set to true, this function will return types that
189139f7f9bSDimitry Andric /// have an local. By default, these types are not returned.
190139f7f9bSDimitry Andric ///
getGlobalVariable(StringRef Name,bool AllowLocal) const1917a7e6055SDimitry Andric GlobalVariable *Module::getGlobalVariable(StringRef Name,
1927a7e6055SDimitry Andric                                           bool AllowLocal) const {
193139f7f9bSDimitry Andric   if (GlobalVariable *Result =
194139f7f9bSDimitry Andric       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
195139f7f9bSDimitry Andric     if (AllowLocal || !Result->hasLocalLinkage())
196139f7f9bSDimitry Andric       return Result;
19791bc56edSDimitry Andric   return nullptr;
198139f7f9bSDimitry Andric }
199139f7f9bSDimitry Andric 
200139f7f9bSDimitry Andric /// getOrInsertGlobal - Look up the specified global in the module symbol table.
201139f7f9bSDimitry Andric ///   1. If it does not exist, add a declaration of the global and return it.
202139f7f9bSDimitry Andric ///   2. Else, the global exists but has the wrong type: return the function
203139f7f9bSDimitry Andric ///      with a constantexpr cast to the right type.
204f785676fSDimitry Andric ///   3. Finally, if the existing global is the correct declaration, return the
205139f7f9bSDimitry Andric ///      existing global.
getOrInsertGlobal(StringRef Name,Type * Ty,function_ref<GlobalVariable * ()> CreateGlobalCallback)206*b5893f02SDimitry Andric Constant *Module::getOrInsertGlobal(
207*b5893f02SDimitry Andric     StringRef Name, Type *Ty,
208*b5893f02SDimitry Andric     function_ref<GlobalVariable *()> CreateGlobalCallback) {
209139f7f9bSDimitry Andric   // See if we have a definition for the specified global already.
210139f7f9bSDimitry Andric   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
211*b5893f02SDimitry Andric   if (!GV)
212*b5893f02SDimitry Andric     GV = CreateGlobalCallback();
213*b5893f02SDimitry Andric   assert(GV && "The CreateGlobalCallback is expected to create a global");
214139f7f9bSDimitry Andric 
215139f7f9bSDimitry Andric   // If the variable exists but has the wrong type, return a bitcast to the
216139f7f9bSDimitry Andric   // right type.
217f785676fSDimitry Andric   Type *GVTy = GV->getType();
218f785676fSDimitry Andric   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
219f785676fSDimitry Andric   if (GVTy != PTy)
220f785676fSDimitry Andric     return ConstantExpr::getBitCast(GV, PTy);
221139f7f9bSDimitry Andric 
222139f7f9bSDimitry Andric   // Otherwise, we just found the existing function or a prototype.
223139f7f9bSDimitry Andric   return GV;
224139f7f9bSDimitry Andric }
225139f7f9bSDimitry Andric 
226*b5893f02SDimitry Andric // Overload to construct a global variable using its constructor's defaults.
getOrInsertGlobal(StringRef Name,Type * Ty)227*b5893f02SDimitry Andric Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
228*b5893f02SDimitry Andric   return getOrInsertGlobal(Name, Ty, [&] {
229*b5893f02SDimitry Andric     return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
230*b5893f02SDimitry Andric                               nullptr, Name);
231*b5893f02SDimitry Andric   });
232*b5893f02SDimitry Andric }
233*b5893f02SDimitry Andric 
234139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
235139f7f9bSDimitry Andric // Methods for easy access to the global variables in the module.
236139f7f9bSDimitry Andric //
237139f7f9bSDimitry Andric 
238139f7f9bSDimitry Andric // getNamedAlias - Look up the specified global in the module symbol table.
239139f7f9bSDimitry Andric // If it does not exist, return null.
240139f7f9bSDimitry Andric //
getNamedAlias(StringRef Name) const241139f7f9bSDimitry Andric GlobalAlias *Module::getNamedAlias(StringRef Name) const {
242139f7f9bSDimitry Andric   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
243139f7f9bSDimitry Andric }
244139f7f9bSDimitry Andric 
getNamedIFunc(StringRef Name) const2453ca95b02SDimitry Andric GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
2463ca95b02SDimitry Andric   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
2473ca95b02SDimitry Andric }
2483ca95b02SDimitry Andric 
249139f7f9bSDimitry Andric /// getNamedMetadata - Return the first NamedMDNode in the module with the
250139f7f9bSDimitry Andric /// specified name. This method returns null if a NamedMDNode with the
251139f7f9bSDimitry Andric /// specified name is not found.
getNamedMetadata(const Twine & Name) const252139f7f9bSDimitry Andric NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
253139f7f9bSDimitry Andric   SmallString<256> NameData;
254139f7f9bSDimitry Andric   StringRef NameRef = Name.toStringRef(NameData);
255139f7f9bSDimitry Andric   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
256139f7f9bSDimitry Andric }
257139f7f9bSDimitry Andric 
258139f7f9bSDimitry Andric /// getOrInsertNamedMetadata - Return the first named MDNode in the module
259139f7f9bSDimitry Andric /// with the specified name. This method returns a new NamedMDNode if a
260139f7f9bSDimitry Andric /// NamedMDNode with the specified name is not found.
getOrInsertNamedMetadata(StringRef Name)261139f7f9bSDimitry Andric NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
262139f7f9bSDimitry Andric   NamedMDNode *&NMD =
263139f7f9bSDimitry Andric     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
264139f7f9bSDimitry Andric   if (!NMD) {
265139f7f9bSDimitry Andric     NMD = new NamedMDNode(Name);
266139f7f9bSDimitry Andric     NMD->setParent(this);
267139f7f9bSDimitry Andric     NamedMDList.push_back(NMD);
268139f7f9bSDimitry Andric   }
269139f7f9bSDimitry Andric   return NMD;
270139f7f9bSDimitry Andric }
271139f7f9bSDimitry Andric 
272139f7f9bSDimitry Andric /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
273139f7f9bSDimitry Andric /// delete it.
eraseNamedMetadata(NamedMDNode * NMD)274139f7f9bSDimitry Andric void Module::eraseNamedMetadata(NamedMDNode *NMD) {
275139f7f9bSDimitry Andric   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
2767d523365SDimitry Andric   NamedMDList.erase(NMD->getIterator());
277139f7f9bSDimitry Andric }
278139f7f9bSDimitry Andric 
isValidModFlagBehavior(Metadata * MD,ModFlagBehavior & MFB)27939d628a0SDimitry Andric bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
280ff0cc061SDimitry Andric   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
28139d628a0SDimitry Andric     uint64_t Val = Behavior->getLimitedValue();
28239d628a0SDimitry Andric     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
28339d628a0SDimitry Andric       MFB = static_cast<ModFlagBehavior>(Val);
28439d628a0SDimitry Andric       return true;
28539d628a0SDimitry Andric     }
28639d628a0SDimitry Andric   }
28739d628a0SDimitry Andric   return false;
28839d628a0SDimitry Andric }
28939d628a0SDimitry Andric 
290139f7f9bSDimitry Andric /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
291139f7f9bSDimitry Andric void Module::
getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> & Flags) const292139f7f9bSDimitry Andric getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
293139f7f9bSDimitry Andric   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
294139f7f9bSDimitry Andric   if (!ModFlags) return;
295139f7f9bSDimitry Andric 
29691bc56edSDimitry Andric   for (const MDNode *Flag : ModFlags->operands()) {
29739d628a0SDimitry Andric     ModFlagBehavior MFB;
29839d628a0SDimitry Andric     if (Flag->getNumOperands() >= 3 &&
29939d628a0SDimitry Andric         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
300ff0cc061SDimitry Andric         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
301f785676fSDimitry Andric       // Check the operands of the MDNode before accessing the operands.
302f785676fSDimitry Andric       // The verifier will actually catch these failures.
303139f7f9bSDimitry Andric       MDString *Key = cast<MDString>(Flag->getOperand(1));
30439d628a0SDimitry Andric       Metadata *Val = Flag->getOperand(2);
30539d628a0SDimitry Andric       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
306139f7f9bSDimitry Andric     }
307139f7f9bSDimitry Andric   }
308f785676fSDimitry Andric }
309f785676fSDimitry Andric 
310f785676fSDimitry Andric /// Return the corresponding value if Key appears in module flags, otherwise
311f785676fSDimitry Andric /// return null.
getModuleFlag(StringRef Key) const31239d628a0SDimitry Andric Metadata *Module::getModuleFlag(StringRef Key) const {
313f785676fSDimitry Andric   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
314f785676fSDimitry Andric   getModuleFlagsMetadata(ModuleFlags);
31591bc56edSDimitry Andric   for (const ModuleFlagEntry &MFE : ModuleFlags) {
316f785676fSDimitry Andric     if (Key == MFE.Key->getString())
317f785676fSDimitry Andric       return MFE.Val;
318f785676fSDimitry Andric   }
31991bc56edSDimitry Andric   return nullptr;
320f785676fSDimitry Andric }
321139f7f9bSDimitry Andric 
322139f7f9bSDimitry Andric /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
323139f7f9bSDimitry Andric /// represents module-level flags. This method returns null if there are no
324139f7f9bSDimitry Andric /// module-level flags.
getModuleFlagsMetadata() const325139f7f9bSDimitry Andric NamedMDNode *Module::getModuleFlagsMetadata() const {
326139f7f9bSDimitry Andric   return getNamedMetadata("llvm.module.flags");
327139f7f9bSDimitry Andric }
328139f7f9bSDimitry Andric 
329139f7f9bSDimitry Andric /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
330139f7f9bSDimitry Andric /// represents module-level flags. If module-level flags aren't found, it
331139f7f9bSDimitry Andric /// creates the named metadata that contains them.
getOrInsertModuleFlagsMetadata()332139f7f9bSDimitry Andric NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
333139f7f9bSDimitry Andric   return getOrInsertNamedMetadata("llvm.module.flags");
334139f7f9bSDimitry Andric }
335139f7f9bSDimitry Andric 
336139f7f9bSDimitry Andric /// addModuleFlag - Add a module-level flag to the module-level flags
337139f7f9bSDimitry Andric /// metadata. It will create the module-level flags named metadata if it doesn't
338139f7f9bSDimitry Andric /// already exist.
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,Metadata * Val)339139f7f9bSDimitry Andric void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
34039d628a0SDimitry Andric                            Metadata *Val) {
341139f7f9bSDimitry Andric   Type *Int32Ty = Type::getInt32Ty(Context);
34239d628a0SDimitry Andric   Metadata *Ops[3] = {
34339d628a0SDimitry Andric       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
34439d628a0SDimitry Andric       MDString::get(Context, Key), Val};
345139f7f9bSDimitry Andric   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
346139f7f9bSDimitry Andric }
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,Constant * Val)347139f7f9bSDimitry Andric void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
34839d628a0SDimitry Andric                            Constant *Val) {
34939d628a0SDimitry Andric   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
35039d628a0SDimitry Andric }
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,uint32_t Val)35139d628a0SDimitry Andric void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
352139f7f9bSDimitry Andric                            uint32_t Val) {
353139f7f9bSDimitry Andric   Type *Int32Ty = Type::getInt32Ty(Context);
354139f7f9bSDimitry Andric   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
355139f7f9bSDimitry Andric }
addModuleFlag(MDNode * Node)356139f7f9bSDimitry Andric void Module::addModuleFlag(MDNode *Node) {
357139f7f9bSDimitry Andric   assert(Node->getNumOperands() == 3 &&
358139f7f9bSDimitry Andric          "Invalid number of operands for module flag!");
35939d628a0SDimitry Andric   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
360139f7f9bSDimitry Andric          isa<MDString>(Node->getOperand(1)) &&
361139f7f9bSDimitry Andric          "Invalid operand types for module flag!");
362139f7f9bSDimitry Andric   getOrInsertModuleFlagsMetadata()->addOperand(Node);
363139f7f9bSDimitry Andric }
364139f7f9bSDimitry Andric 
setDataLayout(StringRef Desc)36591bc56edSDimitry Andric void Module::setDataLayout(StringRef Desc) {
36691bc56edSDimitry Andric   DL.reset(Desc);
36791bc56edSDimitry Andric }
36891bc56edSDimitry Andric 
setDataLayout(const DataLayout & Other)369ff0cc061SDimitry Andric void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
37091bc56edSDimitry Andric 
getDataLayout() const371ff0cc061SDimitry Andric const DataLayout &Module::getDataLayout() const { return DL; }
37291bc56edSDimitry Andric 
operator *() const3733ca95b02SDimitry Andric DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
3743ca95b02SDimitry Andric   return cast<DICompileUnit>(CUs->getOperand(Idx));
3753ca95b02SDimitry Andric }
operator ->() const3763ca95b02SDimitry Andric DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
3773ca95b02SDimitry Andric   return cast<DICompileUnit>(CUs->getOperand(Idx));
3783ca95b02SDimitry Andric }
3793ca95b02SDimitry Andric 
SkipNoDebugCUs()3803ca95b02SDimitry Andric void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
3813ca95b02SDimitry Andric   while (CUs && (Idx < CUs->getNumOperands()) &&
3823ca95b02SDimitry Andric          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
3833ca95b02SDimitry Andric     ++Idx;
3843ca95b02SDimitry Andric }
3853ca95b02SDimitry Andric 
386139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
387139f7f9bSDimitry Andric // Methods to control the materialization of GlobalValues in the Module.
388139f7f9bSDimitry Andric //
setMaterializer(GVMaterializer * GVM)389139f7f9bSDimitry Andric void Module::setMaterializer(GVMaterializer *GVM) {
390139f7f9bSDimitry Andric   assert(!Materializer &&
3917d523365SDimitry Andric          "Module already has a GVMaterializer.  Call materializeAll"
392139f7f9bSDimitry Andric          " to clear it out before setting another one.");
393139f7f9bSDimitry Andric   Materializer.reset(GVM);
394139f7f9bSDimitry Andric }
395139f7f9bSDimitry Andric 
materialize(GlobalValue * GV)396d88c1a5aSDimitry Andric Error Module::materialize(GlobalValue *GV) {
397f785676fSDimitry Andric   if (!Materializer)
398d88c1a5aSDimitry Andric     return Error::success();
399f785676fSDimitry Andric 
40039d628a0SDimitry Andric   return Materializer->materialize(GV);
401139f7f9bSDimitry Andric }
402139f7f9bSDimitry Andric 
materializeAll()403d88c1a5aSDimitry Andric Error Module::materializeAll() {
404139f7f9bSDimitry Andric   if (!Materializer)
405d88c1a5aSDimitry Andric     return Error::success();
4067d523365SDimitry Andric   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
4077d523365SDimitry Andric   return M->materializeModule();
408139f7f9bSDimitry Andric }
409139f7f9bSDimitry Andric 
materializeMetadata()410d88c1a5aSDimitry Andric Error Module::materializeMetadata() {
411ff0cc061SDimitry Andric   if (!Materializer)
412d88c1a5aSDimitry Andric     return Error::success();
413ff0cc061SDimitry Andric   return Materializer->materializeMetadata();
414ff0cc061SDimitry Andric }
415ff0cc061SDimitry Andric 
416139f7f9bSDimitry Andric //===----------------------------------------------------------------------===//
417139f7f9bSDimitry Andric // Other module related stuff.
418139f7f9bSDimitry Andric //
419139f7f9bSDimitry Andric 
getIdentifiedStructTypes() const42039d628a0SDimitry Andric std::vector<StructType *> Module::getIdentifiedStructTypes() const {
42139d628a0SDimitry Andric   // If we have a materializer, it is possible that some unread function
42239d628a0SDimitry Andric   // uses a type that is currently not visible to a TypeFinder, so ask
42339d628a0SDimitry Andric   // the materializer which types it created.
42439d628a0SDimitry Andric   if (Materializer)
42539d628a0SDimitry Andric     return Materializer->getIdentifiedStructTypes();
42639d628a0SDimitry Andric 
42739d628a0SDimitry Andric   std::vector<StructType *> Ret;
42839d628a0SDimitry Andric   TypeFinder SrcStructTypes;
42939d628a0SDimitry Andric   SrcStructTypes.run(*this, true);
43039d628a0SDimitry Andric   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
43139d628a0SDimitry Andric   return Ret;
43239d628a0SDimitry Andric }
433139f7f9bSDimitry Andric 
434139f7f9bSDimitry Andric // dropAllReferences() - This function causes all the subelements to "let go"
435139f7f9bSDimitry Andric // of all references that they are maintaining.  This allows one to 'delete' a
436139f7f9bSDimitry Andric // whole module at a time, even though there may be circular references... first
437139f7f9bSDimitry Andric // all references are dropped, and all use counts go to zero.  Then everything
438139f7f9bSDimitry Andric // is deleted for real.  Note that no operations are valid on an object that
439139f7f9bSDimitry Andric // has "dropped all references", except operator delete.
440139f7f9bSDimitry Andric //
dropAllReferences()441139f7f9bSDimitry Andric void Module::dropAllReferences() {
44291bc56edSDimitry Andric   for (Function &F : *this)
44391bc56edSDimitry Andric     F.dropAllReferences();
444139f7f9bSDimitry Andric 
44591bc56edSDimitry Andric   for (GlobalVariable &GV : globals())
44691bc56edSDimitry Andric     GV.dropAllReferences();
447139f7f9bSDimitry Andric 
44891bc56edSDimitry Andric   for (GlobalAlias &GA : aliases())
44991bc56edSDimitry Andric     GA.dropAllReferences();
4503ca95b02SDimitry Andric 
4513ca95b02SDimitry Andric   for (GlobalIFunc &GIF : ifuncs())
4523ca95b02SDimitry Andric     GIF.dropAllReferences();
45391bc56edSDimitry Andric }
45491bc56edSDimitry Andric 
getNumberRegisterParameters() const4557a7e6055SDimitry Andric unsigned Module::getNumberRegisterParameters() const {
4567a7e6055SDimitry Andric   auto *Val =
4577a7e6055SDimitry Andric       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
4587a7e6055SDimitry Andric   if (!Val)
4597a7e6055SDimitry Andric     return 0;
4607a7e6055SDimitry Andric   return cast<ConstantInt>(Val->getValue())->getZExtValue();
4617a7e6055SDimitry Andric }
4627a7e6055SDimitry Andric 
getDwarfVersion() const46391bc56edSDimitry Andric unsigned Module::getDwarfVersion() const {
46439d628a0SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
46591bc56edSDimitry Andric   if (!Val)
4667d523365SDimitry Andric     return 0;
4677d523365SDimitry Andric   return cast<ConstantInt>(Val->getValue())->getZExtValue();
4687d523365SDimitry Andric }
4697d523365SDimitry Andric 
getCodeViewFlag() const4707d523365SDimitry Andric unsigned Module::getCodeViewFlag() const {
4717d523365SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
4727d523365SDimitry Andric   if (!Val)
4737d523365SDimitry Andric     return 0;
47439d628a0SDimitry Andric   return cast<ConstantInt>(Val->getValue())->getZExtValue();
47591bc56edSDimitry Andric }
47691bc56edSDimitry Andric 
getInstructionCount()4774ba319b5SDimitry Andric unsigned Module::getInstructionCount() {
4784ba319b5SDimitry Andric   unsigned NumInstrs = 0;
4794ba319b5SDimitry Andric   for (Function &F : FunctionList)
4804ba319b5SDimitry Andric     NumInstrs += F.getInstructionCount();
4814ba319b5SDimitry Andric   return NumInstrs;
4824ba319b5SDimitry Andric }
4834ba319b5SDimitry Andric 
getOrInsertComdat(StringRef Name)48491bc56edSDimitry Andric Comdat *Module::getOrInsertComdat(StringRef Name) {
48539d628a0SDimitry Andric   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
48691bc56edSDimitry Andric   Entry.second.Name = &Entry;
48791bc56edSDimitry Andric   return &Entry.second;
488139f7f9bSDimitry Andric }
489404df5bbSDimitry Andric 
getPICLevel() const490404df5bbSDimitry Andric PICLevel::Level Module::getPICLevel() const {
49139d628a0SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
492404df5bbSDimitry Andric 
4937d523365SDimitry Andric   if (!Val)
4943ca95b02SDimitry Andric     return PICLevel::NotPIC;
495404df5bbSDimitry Andric 
49639d628a0SDimitry Andric   return static_cast<PICLevel::Level>(
49739d628a0SDimitry Andric       cast<ConstantInt>(Val->getValue())->getZExtValue());
498404df5bbSDimitry Andric }
499404df5bbSDimitry Andric 
setPICLevel(PICLevel::Level PL)500404df5bbSDimitry Andric void Module::setPICLevel(PICLevel::Level PL) {
501302affcbSDimitry Andric   addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
502404df5bbSDimitry Andric }
5037d523365SDimitry Andric 
getPIELevel() const5043ca95b02SDimitry Andric PIELevel::Level Module::getPIELevel() const {
5053ca95b02SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
5063ca95b02SDimitry Andric 
5073ca95b02SDimitry Andric   if (!Val)
5083ca95b02SDimitry Andric     return PIELevel::Default;
5093ca95b02SDimitry Andric 
5103ca95b02SDimitry Andric   return static_cast<PIELevel::Level>(
5113ca95b02SDimitry Andric       cast<ConstantInt>(Val->getValue())->getZExtValue());
5127d523365SDimitry Andric }
5137d523365SDimitry Andric 
setPIELevel(PIELevel::Level PL)5143ca95b02SDimitry Andric void Module::setPIELevel(PIELevel::Level PL) {
515302affcbSDimitry Andric   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
5163ca95b02SDimitry Andric }
5173ca95b02SDimitry Andric 
getCodeModel() const518*b5893f02SDimitry Andric Optional<CodeModel::Model> Module::getCodeModel() const {
519*b5893f02SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
520*b5893f02SDimitry Andric 
521*b5893f02SDimitry Andric   if (!Val)
522*b5893f02SDimitry Andric     return None;
523*b5893f02SDimitry Andric 
524*b5893f02SDimitry Andric   return static_cast<CodeModel::Model>(
525*b5893f02SDimitry Andric       cast<ConstantInt>(Val->getValue())->getZExtValue());
526*b5893f02SDimitry Andric }
527*b5893f02SDimitry Andric 
setCodeModel(CodeModel::Model CL)528*b5893f02SDimitry Andric void Module::setCodeModel(CodeModel::Model CL) {
529*b5893f02SDimitry Andric   // Linking object files with different code models is undefined behavior
530*b5893f02SDimitry Andric   // because the compiler would have to generate additional code (to span
531*b5893f02SDimitry Andric   // longer jumps) if a larger code model is used with a smaller one.
532*b5893f02SDimitry Andric   // Therefore we will treat attempts to mix code models as an error.
533*b5893f02SDimitry Andric   addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
534*b5893f02SDimitry Andric }
535*b5893f02SDimitry Andric 
setProfileSummary(Metadata * M)5363ca95b02SDimitry Andric void Module::setProfileSummary(Metadata *M) {
5373ca95b02SDimitry Andric   addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
5383ca95b02SDimitry Andric }
5393ca95b02SDimitry Andric 
getProfileSummary()5403ca95b02SDimitry Andric Metadata *Module::getProfileSummary() {
5413ca95b02SDimitry Andric   return getModuleFlag("ProfileSummary");
5423ca95b02SDimitry Andric }
5433ca95b02SDimitry Andric 
setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB)544d88c1a5aSDimitry Andric void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
545d88c1a5aSDimitry Andric   OwnedMemoryBuffer = std::move(MB);
546d88c1a5aSDimitry Andric }
547d88c1a5aSDimitry Andric 
getRtLibUseGOT() const5484ba319b5SDimitry Andric bool Module::getRtLibUseGOT() const {
5494ba319b5SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
5504ba319b5SDimitry Andric   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
5514ba319b5SDimitry Andric }
5524ba319b5SDimitry Andric 
setRtLibUseGOT()5534ba319b5SDimitry Andric void Module::setRtLibUseGOT() {
5544ba319b5SDimitry Andric   addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
5554ba319b5SDimitry Andric }
5564ba319b5SDimitry Andric 
setSDKVersion(const VersionTuple & V)557*b5893f02SDimitry Andric void Module::setSDKVersion(const VersionTuple &V) {
558*b5893f02SDimitry Andric   SmallVector<unsigned, 3> Entries;
559*b5893f02SDimitry Andric   Entries.push_back(V.getMajor());
560*b5893f02SDimitry Andric   if (auto Minor = V.getMinor()) {
561*b5893f02SDimitry Andric     Entries.push_back(*Minor);
562*b5893f02SDimitry Andric     if (auto Subminor = V.getSubminor())
563*b5893f02SDimitry Andric       Entries.push_back(*Subminor);
564*b5893f02SDimitry Andric     // Ignore the 'build' component as it can't be represented in the object
565*b5893f02SDimitry Andric     // file.
566*b5893f02SDimitry Andric   }
567*b5893f02SDimitry Andric   addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
568*b5893f02SDimitry Andric                 ConstantDataArray::get(Context, Entries));
569*b5893f02SDimitry Andric }
570*b5893f02SDimitry Andric 
getSDKVersion() const571*b5893f02SDimitry Andric VersionTuple Module::getSDKVersion() const {
572*b5893f02SDimitry Andric   auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
573*b5893f02SDimitry Andric   if (!CM)
574*b5893f02SDimitry Andric     return {};
575*b5893f02SDimitry Andric   auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
576*b5893f02SDimitry Andric   if (!Arr)
577*b5893f02SDimitry Andric     return {};
578*b5893f02SDimitry Andric   auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
579*b5893f02SDimitry Andric     if (Index >= Arr->getNumElements())
580*b5893f02SDimitry Andric       return None;
581*b5893f02SDimitry Andric     return (unsigned)Arr->getElementAsInteger(Index);
582*b5893f02SDimitry Andric   };
583*b5893f02SDimitry Andric   auto Major = getVersionComponent(0);
584*b5893f02SDimitry Andric   if (!Major)
585*b5893f02SDimitry Andric     return {};
586*b5893f02SDimitry Andric   VersionTuple Result = VersionTuple(*Major);
587*b5893f02SDimitry Andric   if (auto Minor = getVersionComponent(1)) {
588*b5893f02SDimitry Andric     Result = VersionTuple(*Major, *Minor);
589*b5893f02SDimitry Andric     if (auto Subminor = getVersionComponent(2)) {
590*b5893f02SDimitry Andric       Result = VersionTuple(*Major, *Minor, *Subminor);
591*b5893f02SDimitry Andric     }
592*b5893f02SDimitry Andric   }
593*b5893f02SDimitry Andric   return Result;
594*b5893f02SDimitry Andric }
595*b5893f02SDimitry Andric 
collectUsedGlobalVariables(const Module & M,SmallPtrSetImpl<GlobalValue * > & Set,bool CompilerUsed)5963ca95b02SDimitry Andric GlobalVariable *llvm::collectUsedGlobalVariables(
5973ca95b02SDimitry Andric     const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
5983ca95b02SDimitry Andric   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
5993ca95b02SDimitry Andric   GlobalVariable *GV = M.getGlobalVariable(Name);
6003ca95b02SDimitry Andric   if (!GV || !GV->hasInitializer())
6013ca95b02SDimitry Andric     return GV;
6023ca95b02SDimitry Andric 
6033ca95b02SDimitry Andric   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
6043ca95b02SDimitry Andric   for (Value *Op : Init->operands()) {
6053ca95b02SDimitry Andric     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
6063ca95b02SDimitry Andric     Set.insert(G);
6073ca95b02SDimitry Andric   }
6083ca95b02SDimitry Andric   return GV;
6097d523365SDimitry Andric }
610