xref: /freebsd/contrib/llvm-project/llvm/lib/IR/Module.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===- Module.cpp - Implement the Module class ----------------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file implements the Module class for the IR library.
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
14*0b57cec5SDimitry Andric #include "SymbolTableListTraitsImpl.h"
15*0b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
20*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
21*0b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
22*0b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
23*0b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
24*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
25*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
26*0b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
27*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
28*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
29*0b57cec5SDimitry Andric #include "llvm/IR/GVMaterializer.h"
30*0b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
31*0b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
32*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
34*0b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
35*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/SymbolTableListTraits.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/Type.h"
38*0b57cec5SDimitry Andric #include "llvm/IR/TypeFinder.h"
39*0b57cec5SDimitry Andric #include "llvm/IR/Value.h"
40*0b57cec5SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
41*0b57cec5SDimitry Andric #include "llvm/Pass.h"
42*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
43*0b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
44*0b57cec5SDimitry Andric #include "llvm/Support/Error.h"
45*0b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
46*0b57cec5SDimitry Andric #include "llvm/Support/Path.h"
47*0b57cec5SDimitry Andric #include "llvm/Support/RandomNumberGenerator.h"
48*0b57cec5SDimitry Andric #include "llvm/Support/VersionTuple.h"
49*0b57cec5SDimitry Andric #include <algorithm>
50*0b57cec5SDimitry Andric #include <cassert>
51*0b57cec5SDimitry Andric #include <cstdint>
52*0b57cec5SDimitry Andric #include <memory>
53*0b57cec5SDimitry Andric #include <utility>
54*0b57cec5SDimitry Andric #include <vector>
55*0b57cec5SDimitry Andric 
56*0b57cec5SDimitry Andric using namespace llvm;
57*0b57cec5SDimitry Andric 
58*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
59*0b57cec5SDimitry Andric // Methods to implement the globals and functions lists.
60*0b57cec5SDimitry Andric //
61*0b57cec5SDimitry Andric 
62*0b57cec5SDimitry Andric // Explicit instantiations of SymbolTableListTraits since some of the methods
63*0b57cec5SDimitry Andric // are not in the public header file.
64*0b57cec5SDimitry Andric template class llvm::SymbolTableListTraits<Function>;
65*0b57cec5SDimitry Andric template class llvm::SymbolTableListTraits<GlobalVariable>;
66*0b57cec5SDimitry Andric template class llvm::SymbolTableListTraits<GlobalAlias>;
67*0b57cec5SDimitry Andric template class llvm::SymbolTableListTraits<GlobalIFunc>;
68*0b57cec5SDimitry Andric 
69*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
70*0b57cec5SDimitry Andric // Primitive Module methods.
71*0b57cec5SDimitry Andric //
72*0b57cec5SDimitry Andric 
73*0b57cec5SDimitry Andric Module::Module(StringRef MID, LLVMContext &C)
74*0b57cec5SDimitry Andric     : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
75*0b57cec5SDimitry Andric   ValSymTab = new ValueSymbolTable();
76*0b57cec5SDimitry Andric   NamedMDSymTab = new StringMap<NamedMDNode *>();
77*0b57cec5SDimitry Andric   Context.addModule(this);
78*0b57cec5SDimitry Andric }
79*0b57cec5SDimitry Andric 
80*0b57cec5SDimitry Andric Module::~Module() {
81*0b57cec5SDimitry Andric   Context.removeModule(this);
82*0b57cec5SDimitry Andric   dropAllReferences();
83*0b57cec5SDimitry Andric   GlobalList.clear();
84*0b57cec5SDimitry Andric   FunctionList.clear();
85*0b57cec5SDimitry Andric   AliasList.clear();
86*0b57cec5SDimitry Andric   IFuncList.clear();
87*0b57cec5SDimitry Andric   NamedMDList.clear();
88*0b57cec5SDimitry Andric   delete ValSymTab;
89*0b57cec5SDimitry Andric   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
90*0b57cec5SDimitry Andric }
91*0b57cec5SDimitry Andric 
92*0b57cec5SDimitry Andric std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
93*0b57cec5SDimitry Andric   SmallString<32> Salt(P->getPassName());
94*0b57cec5SDimitry Andric 
95*0b57cec5SDimitry Andric   // This RNG is guaranteed to produce the same random stream only
96*0b57cec5SDimitry Andric   // when the Module ID and thus the input filename is the same. This
97*0b57cec5SDimitry Andric   // might be problematic if the input filename extension changes
98*0b57cec5SDimitry Andric   // (e.g. from .c to .bc or .ll).
99*0b57cec5SDimitry Andric   //
100*0b57cec5SDimitry Andric   // We could store this salt in NamedMetadata, but this would make
101*0b57cec5SDimitry Andric   // the parameter non-const. This would unfortunately make this
102*0b57cec5SDimitry Andric   // interface unusable by any Machine passes, since they only have a
103*0b57cec5SDimitry Andric   // const reference to their IR Module. Alternatively we can always
104*0b57cec5SDimitry Andric   // store salt metadata from the Module constructor.
105*0b57cec5SDimitry Andric   Salt += sys::path::filename(getModuleIdentifier());
106*0b57cec5SDimitry Andric 
107*0b57cec5SDimitry Andric   return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt));
108*0b57cec5SDimitry Andric }
109*0b57cec5SDimitry Andric 
110*0b57cec5SDimitry Andric /// getNamedValue - Return the first global value in the module with
111*0b57cec5SDimitry Andric /// the specified name, of arbitrary type.  This method returns null
112*0b57cec5SDimitry Andric /// if a global with the specified name is not found.
113*0b57cec5SDimitry Andric GlobalValue *Module::getNamedValue(StringRef Name) const {
114*0b57cec5SDimitry Andric   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
115*0b57cec5SDimitry Andric }
116*0b57cec5SDimitry Andric 
117*0b57cec5SDimitry Andric /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
118*0b57cec5SDimitry Andric /// This ID is uniqued across modules in the current LLVMContext.
119*0b57cec5SDimitry Andric unsigned Module::getMDKindID(StringRef Name) const {
120*0b57cec5SDimitry Andric   return Context.getMDKindID(Name);
121*0b57cec5SDimitry Andric }
122*0b57cec5SDimitry Andric 
123*0b57cec5SDimitry Andric /// getMDKindNames - Populate client supplied SmallVector with the name for
124*0b57cec5SDimitry Andric /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
125*0b57cec5SDimitry Andric /// so it is filled in as an empty string.
126*0b57cec5SDimitry Andric void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
127*0b57cec5SDimitry Andric   return Context.getMDKindNames(Result);
128*0b57cec5SDimitry Andric }
129*0b57cec5SDimitry Andric 
130*0b57cec5SDimitry Andric void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
131*0b57cec5SDimitry Andric   return Context.getOperandBundleTags(Result);
132*0b57cec5SDimitry Andric }
133*0b57cec5SDimitry Andric 
134*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
135*0b57cec5SDimitry Andric // Methods for easy access to the functions in the module.
136*0b57cec5SDimitry Andric //
137*0b57cec5SDimitry Andric 
138*0b57cec5SDimitry Andric // getOrInsertFunction - Look up the specified function in the module symbol
139*0b57cec5SDimitry Andric // table.  If it does not exist, add a prototype for the function and return
140*0b57cec5SDimitry Andric // it.  This is nice because it allows most passes to get away with not handling
141*0b57cec5SDimitry Andric // the symbol table directly for this common task.
142*0b57cec5SDimitry Andric //
143*0b57cec5SDimitry Andric FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
144*0b57cec5SDimitry Andric                                            AttributeList AttributeList) {
145*0b57cec5SDimitry Andric   // See if we have a definition for the specified function already.
146*0b57cec5SDimitry Andric   GlobalValue *F = getNamedValue(Name);
147*0b57cec5SDimitry Andric   if (!F) {
148*0b57cec5SDimitry Andric     // Nope, add it
149*0b57cec5SDimitry Andric     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
150*0b57cec5SDimitry Andric                                      DL.getProgramAddressSpace(), Name);
151*0b57cec5SDimitry Andric     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
152*0b57cec5SDimitry Andric       New->setAttributes(AttributeList);
153*0b57cec5SDimitry Andric     FunctionList.push_back(New);
154*0b57cec5SDimitry Andric     return {Ty, New}; // Return the new prototype.
155*0b57cec5SDimitry Andric   }
156*0b57cec5SDimitry Andric 
157*0b57cec5SDimitry Andric   // If the function exists but has the wrong type, return a bitcast to the
158*0b57cec5SDimitry Andric   // right type.
159*0b57cec5SDimitry Andric   auto *PTy = PointerType::get(Ty, F->getAddressSpace());
160*0b57cec5SDimitry Andric   if (F->getType() != PTy)
161*0b57cec5SDimitry Andric     return {Ty, ConstantExpr::getBitCast(F, PTy)};
162*0b57cec5SDimitry Andric 
163*0b57cec5SDimitry Andric   // Otherwise, we just found the existing function or a prototype.
164*0b57cec5SDimitry Andric   return {Ty, F};
165*0b57cec5SDimitry Andric }
166*0b57cec5SDimitry Andric 
167*0b57cec5SDimitry Andric FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
168*0b57cec5SDimitry Andric   return getOrInsertFunction(Name, Ty, AttributeList());
169*0b57cec5SDimitry Andric }
170*0b57cec5SDimitry Andric 
171*0b57cec5SDimitry Andric // getFunction - Look up the specified function in the module symbol table.
172*0b57cec5SDimitry Andric // If it does not exist, return null.
173*0b57cec5SDimitry Andric //
174*0b57cec5SDimitry Andric Function *Module::getFunction(StringRef Name) const {
175*0b57cec5SDimitry Andric   return dyn_cast_or_null<Function>(getNamedValue(Name));
176*0b57cec5SDimitry Andric }
177*0b57cec5SDimitry Andric 
178*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
179*0b57cec5SDimitry Andric // Methods for easy access to the global variables in the module.
180*0b57cec5SDimitry Andric //
181*0b57cec5SDimitry Andric 
182*0b57cec5SDimitry Andric /// getGlobalVariable - Look up the specified global variable in the module
183*0b57cec5SDimitry Andric /// symbol table.  If it does not exist, return null.  The type argument
184*0b57cec5SDimitry Andric /// should be the underlying type of the global, i.e., it should not have
185*0b57cec5SDimitry Andric /// the top-level PointerType, which represents the address of the global.
186*0b57cec5SDimitry Andric /// If AllowLocal is set to true, this function will return types that
187*0b57cec5SDimitry Andric /// have an local. By default, these types are not returned.
188*0b57cec5SDimitry Andric ///
189*0b57cec5SDimitry Andric GlobalVariable *Module::getGlobalVariable(StringRef Name,
190*0b57cec5SDimitry Andric                                           bool AllowLocal) const {
191*0b57cec5SDimitry Andric   if (GlobalVariable *Result =
192*0b57cec5SDimitry Andric       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
193*0b57cec5SDimitry Andric     if (AllowLocal || !Result->hasLocalLinkage())
194*0b57cec5SDimitry Andric       return Result;
195*0b57cec5SDimitry Andric   return nullptr;
196*0b57cec5SDimitry Andric }
197*0b57cec5SDimitry Andric 
198*0b57cec5SDimitry Andric /// getOrInsertGlobal - Look up the specified global in the module symbol table.
199*0b57cec5SDimitry Andric ///   1. If it does not exist, add a declaration of the global and return it.
200*0b57cec5SDimitry Andric ///   2. Else, the global exists but has the wrong type: return the function
201*0b57cec5SDimitry Andric ///      with a constantexpr cast to the right type.
202*0b57cec5SDimitry Andric ///   3. Finally, if the existing global is the correct declaration, return the
203*0b57cec5SDimitry Andric ///      existing global.
204*0b57cec5SDimitry Andric Constant *Module::getOrInsertGlobal(
205*0b57cec5SDimitry Andric     StringRef Name, Type *Ty,
206*0b57cec5SDimitry Andric     function_ref<GlobalVariable *()> CreateGlobalCallback) {
207*0b57cec5SDimitry Andric   // See if we have a definition for the specified global already.
208*0b57cec5SDimitry Andric   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
209*0b57cec5SDimitry Andric   if (!GV)
210*0b57cec5SDimitry Andric     GV = CreateGlobalCallback();
211*0b57cec5SDimitry Andric   assert(GV && "The CreateGlobalCallback is expected to create a global");
212*0b57cec5SDimitry Andric 
213*0b57cec5SDimitry Andric   // If the variable exists but has the wrong type, return a bitcast to the
214*0b57cec5SDimitry Andric   // right type.
215*0b57cec5SDimitry Andric   Type *GVTy = GV->getType();
216*0b57cec5SDimitry Andric   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
217*0b57cec5SDimitry Andric   if (GVTy != PTy)
218*0b57cec5SDimitry Andric     return ConstantExpr::getBitCast(GV, PTy);
219*0b57cec5SDimitry Andric 
220*0b57cec5SDimitry Andric   // Otherwise, we just found the existing function or a prototype.
221*0b57cec5SDimitry Andric   return GV;
222*0b57cec5SDimitry Andric }
223*0b57cec5SDimitry Andric 
224*0b57cec5SDimitry Andric // Overload to construct a global variable using its constructor's defaults.
225*0b57cec5SDimitry Andric Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
226*0b57cec5SDimitry Andric   return getOrInsertGlobal(Name, Ty, [&] {
227*0b57cec5SDimitry Andric     return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
228*0b57cec5SDimitry Andric                               nullptr, Name);
229*0b57cec5SDimitry Andric   });
230*0b57cec5SDimitry Andric }
231*0b57cec5SDimitry Andric 
232*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
233*0b57cec5SDimitry Andric // Methods for easy access to the global variables in the module.
234*0b57cec5SDimitry Andric //
235*0b57cec5SDimitry Andric 
236*0b57cec5SDimitry Andric // getNamedAlias - Look up the specified global in the module symbol table.
237*0b57cec5SDimitry Andric // If it does not exist, return null.
238*0b57cec5SDimitry Andric //
239*0b57cec5SDimitry Andric GlobalAlias *Module::getNamedAlias(StringRef Name) const {
240*0b57cec5SDimitry Andric   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
241*0b57cec5SDimitry Andric }
242*0b57cec5SDimitry Andric 
243*0b57cec5SDimitry Andric GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
244*0b57cec5SDimitry Andric   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
245*0b57cec5SDimitry Andric }
246*0b57cec5SDimitry Andric 
247*0b57cec5SDimitry Andric /// getNamedMetadata - Return the first NamedMDNode in the module with the
248*0b57cec5SDimitry Andric /// specified name. This method returns null if a NamedMDNode with the
249*0b57cec5SDimitry Andric /// specified name is not found.
250*0b57cec5SDimitry Andric NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
251*0b57cec5SDimitry Andric   SmallString<256> NameData;
252*0b57cec5SDimitry Andric   StringRef NameRef = Name.toStringRef(NameData);
253*0b57cec5SDimitry Andric   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
254*0b57cec5SDimitry Andric }
255*0b57cec5SDimitry Andric 
256*0b57cec5SDimitry Andric /// getOrInsertNamedMetadata - Return the first named MDNode in the module
257*0b57cec5SDimitry Andric /// with the specified name. This method returns a new NamedMDNode if a
258*0b57cec5SDimitry Andric /// NamedMDNode with the specified name is not found.
259*0b57cec5SDimitry Andric NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
260*0b57cec5SDimitry Andric   NamedMDNode *&NMD =
261*0b57cec5SDimitry Andric     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
262*0b57cec5SDimitry Andric   if (!NMD) {
263*0b57cec5SDimitry Andric     NMD = new NamedMDNode(Name);
264*0b57cec5SDimitry Andric     NMD->setParent(this);
265*0b57cec5SDimitry Andric     NamedMDList.push_back(NMD);
266*0b57cec5SDimitry Andric   }
267*0b57cec5SDimitry Andric   return NMD;
268*0b57cec5SDimitry Andric }
269*0b57cec5SDimitry Andric 
270*0b57cec5SDimitry Andric /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
271*0b57cec5SDimitry Andric /// delete it.
272*0b57cec5SDimitry Andric void Module::eraseNamedMetadata(NamedMDNode *NMD) {
273*0b57cec5SDimitry Andric   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
274*0b57cec5SDimitry Andric   NamedMDList.erase(NMD->getIterator());
275*0b57cec5SDimitry Andric }
276*0b57cec5SDimitry Andric 
277*0b57cec5SDimitry Andric bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
278*0b57cec5SDimitry Andric   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
279*0b57cec5SDimitry Andric     uint64_t Val = Behavior->getLimitedValue();
280*0b57cec5SDimitry Andric     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
281*0b57cec5SDimitry Andric       MFB = static_cast<ModFlagBehavior>(Val);
282*0b57cec5SDimitry Andric       return true;
283*0b57cec5SDimitry Andric     }
284*0b57cec5SDimitry Andric   }
285*0b57cec5SDimitry Andric   return false;
286*0b57cec5SDimitry Andric }
287*0b57cec5SDimitry Andric 
288*0b57cec5SDimitry Andric /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
289*0b57cec5SDimitry Andric void Module::
290*0b57cec5SDimitry Andric getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
291*0b57cec5SDimitry Andric   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
292*0b57cec5SDimitry Andric   if (!ModFlags) return;
293*0b57cec5SDimitry Andric 
294*0b57cec5SDimitry Andric   for (const MDNode *Flag : ModFlags->operands()) {
295*0b57cec5SDimitry Andric     ModFlagBehavior MFB;
296*0b57cec5SDimitry Andric     if (Flag->getNumOperands() >= 3 &&
297*0b57cec5SDimitry Andric         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
298*0b57cec5SDimitry Andric         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
299*0b57cec5SDimitry Andric       // Check the operands of the MDNode before accessing the operands.
300*0b57cec5SDimitry Andric       // The verifier will actually catch these failures.
301*0b57cec5SDimitry Andric       MDString *Key = cast<MDString>(Flag->getOperand(1));
302*0b57cec5SDimitry Andric       Metadata *Val = Flag->getOperand(2);
303*0b57cec5SDimitry Andric       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
304*0b57cec5SDimitry Andric     }
305*0b57cec5SDimitry Andric   }
306*0b57cec5SDimitry Andric }
307*0b57cec5SDimitry Andric 
308*0b57cec5SDimitry Andric /// Return the corresponding value if Key appears in module flags, otherwise
309*0b57cec5SDimitry Andric /// return null.
310*0b57cec5SDimitry Andric Metadata *Module::getModuleFlag(StringRef Key) const {
311*0b57cec5SDimitry Andric   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
312*0b57cec5SDimitry Andric   getModuleFlagsMetadata(ModuleFlags);
313*0b57cec5SDimitry Andric   for (const ModuleFlagEntry &MFE : ModuleFlags) {
314*0b57cec5SDimitry Andric     if (Key == MFE.Key->getString())
315*0b57cec5SDimitry Andric       return MFE.Val;
316*0b57cec5SDimitry Andric   }
317*0b57cec5SDimitry Andric   return nullptr;
318*0b57cec5SDimitry Andric }
319*0b57cec5SDimitry Andric 
320*0b57cec5SDimitry Andric /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
321*0b57cec5SDimitry Andric /// represents module-level flags. This method returns null if there are no
322*0b57cec5SDimitry Andric /// module-level flags.
323*0b57cec5SDimitry Andric NamedMDNode *Module::getModuleFlagsMetadata() const {
324*0b57cec5SDimitry Andric   return getNamedMetadata("llvm.module.flags");
325*0b57cec5SDimitry Andric }
326*0b57cec5SDimitry Andric 
327*0b57cec5SDimitry Andric /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
328*0b57cec5SDimitry Andric /// represents module-level flags. If module-level flags aren't found, it
329*0b57cec5SDimitry Andric /// creates the named metadata that contains them.
330*0b57cec5SDimitry Andric NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
331*0b57cec5SDimitry Andric   return getOrInsertNamedMetadata("llvm.module.flags");
332*0b57cec5SDimitry Andric }
333*0b57cec5SDimitry Andric 
334*0b57cec5SDimitry Andric /// addModuleFlag - Add a module-level flag to the module-level flags
335*0b57cec5SDimitry Andric /// metadata. It will create the module-level flags named metadata if it doesn't
336*0b57cec5SDimitry Andric /// already exist.
337*0b57cec5SDimitry Andric void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
338*0b57cec5SDimitry Andric                            Metadata *Val) {
339*0b57cec5SDimitry Andric   Type *Int32Ty = Type::getInt32Ty(Context);
340*0b57cec5SDimitry Andric   Metadata *Ops[3] = {
341*0b57cec5SDimitry Andric       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
342*0b57cec5SDimitry Andric       MDString::get(Context, Key), Val};
343*0b57cec5SDimitry Andric   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
344*0b57cec5SDimitry Andric }
345*0b57cec5SDimitry Andric void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
346*0b57cec5SDimitry Andric                            Constant *Val) {
347*0b57cec5SDimitry Andric   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
348*0b57cec5SDimitry Andric }
349*0b57cec5SDimitry Andric void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
350*0b57cec5SDimitry Andric                            uint32_t Val) {
351*0b57cec5SDimitry Andric   Type *Int32Ty = Type::getInt32Ty(Context);
352*0b57cec5SDimitry Andric   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
353*0b57cec5SDimitry Andric }
354*0b57cec5SDimitry Andric void Module::addModuleFlag(MDNode *Node) {
355*0b57cec5SDimitry Andric   assert(Node->getNumOperands() == 3 &&
356*0b57cec5SDimitry Andric          "Invalid number of operands for module flag!");
357*0b57cec5SDimitry Andric   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
358*0b57cec5SDimitry Andric          isa<MDString>(Node->getOperand(1)) &&
359*0b57cec5SDimitry Andric          "Invalid operand types for module flag!");
360*0b57cec5SDimitry Andric   getOrInsertModuleFlagsMetadata()->addOperand(Node);
361*0b57cec5SDimitry Andric }
362*0b57cec5SDimitry Andric 
363*0b57cec5SDimitry Andric void Module::setDataLayout(StringRef Desc) {
364*0b57cec5SDimitry Andric   DL.reset(Desc);
365*0b57cec5SDimitry Andric }
366*0b57cec5SDimitry Andric 
367*0b57cec5SDimitry Andric void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
368*0b57cec5SDimitry Andric 
369*0b57cec5SDimitry Andric const DataLayout &Module::getDataLayout() const { return DL; }
370*0b57cec5SDimitry Andric 
371*0b57cec5SDimitry Andric DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
372*0b57cec5SDimitry Andric   return cast<DICompileUnit>(CUs->getOperand(Idx));
373*0b57cec5SDimitry Andric }
374*0b57cec5SDimitry Andric DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
375*0b57cec5SDimitry Andric   return cast<DICompileUnit>(CUs->getOperand(Idx));
376*0b57cec5SDimitry Andric }
377*0b57cec5SDimitry Andric 
378*0b57cec5SDimitry Andric void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
379*0b57cec5SDimitry Andric   while (CUs && (Idx < CUs->getNumOperands()) &&
380*0b57cec5SDimitry Andric          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
381*0b57cec5SDimitry Andric     ++Idx;
382*0b57cec5SDimitry Andric }
383*0b57cec5SDimitry Andric 
384*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
385*0b57cec5SDimitry Andric // Methods to control the materialization of GlobalValues in the Module.
386*0b57cec5SDimitry Andric //
387*0b57cec5SDimitry Andric void Module::setMaterializer(GVMaterializer *GVM) {
388*0b57cec5SDimitry Andric   assert(!Materializer &&
389*0b57cec5SDimitry Andric          "Module already has a GVMaterializer.  Call materializeAll"
390*0b57cec5SDimitry Andric          " to clear it out before setting another one.");
391*0b57cec5SDimitry Andric   Materializer.reset(GVM);
392*0b57cec5SDimitry Andric }
393*0b57cec5SDimitry Andric 
394*0b57cec5SDimitry Andric Error Module::materialize(GlobalValue *GV) {
395*0b57cec5SDimitry Andric   if (!Materializer)
396*0b57cec5SDimitry Andric     return Error::success();
397*0b57cec5SDimitry Andric 
398*0b57cec5SDimitry Andric   return Materializer->materialize(GV);
399*0b57cec5SDimitry Andric }
400*0b57cec5SDimitry Andric 
401*0b57cec5SDimitry Andric Error Module::materializeAll() {
402*0b57cec5SDimitry Andric   if (!Materializer)
403*0b57cec5SDimitry Andric     return Error::success();
404*0b57cec5SDimitry Andric   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
405*0b57cec5SDimitry Andric   return M->materializeModule();
406*0b57cec5SDimitry Andric }
407*0b57cec5SDimitry Andric 
408*0b57cec5SDimitry Andric Error Module::materializeMetadata() {
409*0b57cec5SDimitry Andric   if (!Materializer)
410*0b57cec5SDimitry Andric     return Error::success();
411*0b57cec5SDimitry Andric   return Materializer->materializeMetadata();
412*0b57cec5SDimitry Andric }
413*0b57cec5SDimitry Andric 
414*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
415*0b57cec5SDimitry Andric // Other module related stuff.
416*0b57cec5SDimitry Andric //
417*0b57cec5SDimitry Andric 
418*0b57cec5SDimitry Andric std::vector<StructType *> Module::getIdentifiedStructTypes() const {
419*0b57cec5SDimitry Andric   // If we have a materializer, it is possible that some unread function
420*0b57cec5SDimitry Andric   // uses a type that is currently not visible to a TypeFinder, so ask
421*0b57cec5SDimitry Andric   // the materializer which types it created.
422*0b57cec5SDimitry Andric   if (Materializer)
423*0b57cec5SDimitry Andric     return Materializer->getIdentifiedStructTypes();
424*0b57cec5SDimitry Andric 
425*0b57cec5SDimitry Andric   std::vector<StructType *> Ret;
426*0b57cec5SDimitry Andric   TypeFinder SrcStructTypes;
427*0b57cec5SDimitry Andric   SrcStructTypes.run(*this, true);
428*0b57cec5SDimitry Andric   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
429*0b57cec5SDimitry Andric   return Ret;
430*0b57cec5SDimitry Andric }
431*0b57cec5SDimitry Andric 
432*0b57cec5SDimitry Andric // dropAllReferences() - This function causes all the subelements to "let go"
433*0b57cec5SDimitry Andric // of all references that they are maintaining.  This allows one to 'delete' a
434*0b57cec5SDimitry Andric // whole module at a time, even though there may be circular references... first
435*0b57cec5SDimitry Andric // all references are dropped, and all use counts go to zero.  Then everything
436*0b57cec5SDimitry Andric // is deleted for real.  Note that no operations are valid on an object that
437*0b57cec5SDimitry Andric // has "dropped all references", except operator delete.
438*0b57cec5SDimitry Andric //
439*0b57cec5SDimitry Andric void Module::dropAllReferences() {
440*0b57cec5SDimitry Andric   for (Function &F : *this)
441*0b57cec5SDimitry Andric     F.dropAllReferences();
442*0b57cec5SDimitry Andric 
443*0b57cec5SDimitry Andric   for (GlobalVariable &GV : globals())
444*0b57cec5SDimitry Andric     GV.dropAllReferences();
445*0b57cec5SDimitry Andric 
446*0b57cec5SDimitry Andric   for (GlobalAlias &GA : aliases())
447*0b57cec5SDimitry Andric     GA.dropAllReferences();
448*0b57cec5SDimitry Andric 
449*0b57cec5SDimitry Andric   for (GlobalIFunc &GIF : ifuncs())
450*0b57cec5SDimitry Andric     GIF.dropAllReferences();
451*0b57cec5SDimitry Andric }
452*0b57cec5SDimitry Andric 
453*0b57cec5SDimitry Andric unsigned Module::getNumberRegisterParameters() const {
454*0b57cec5SDimitry Andric   auto *Val =
455*0b57cec5SDimitry Andric       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
456*0b57cec5SDimitry Andric   if (!Val)
457*0b57cec5SDimitry Andric     return 0;
458*0b57cec5SDimitry Andric   return cast<ConstantInt>(Val->getValue())->getZExtValue();
459*0b57cec5SDimitry Andric }
460*0b57cec5SDimitry Andric 
461*0b57cec5SDimitry Andric unsigned Module::getDwarfVersion() const {
462*0b57cec5SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
463*0b57cec5SDimitry Andric   if (!Val)
464*0b57cec5SDimitry Andric     return 0;
465*0b57cec5SDimitry Andric   return cast<ConstantInt>(Val->getValue())->getZExtValue();
466*0b57cec5SDimitry Andric }
467*0b57cec5SDimitry Andric 
468*0b57cec5SDimitry Andric unsigned Module::getCodeViewFlag() const {
469*0b57cec5SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
470*0b57cec5SDimitry Andric   if (!Val)
471*0b57cec5SDimitry Andric     return 0;
472*0b57cec5SDimitry Andric   return cast<ConstantInt>(Val->getValue())->getZExtValue();
473*0b57cec5SDimitry Andric }
474*0b57cec5SDimitry Andric 
475*0b57cec5SDimitry Andric unsigned Module::getInstructionCount() {
476*0b57cec5SDimitry Andric   unsigned NumInstrs = 0;
477*0b57cec5SDimitry Andric   for (Function &F : FunctionList)
478*0b57cec5SDimitry Andric     NumInstrs += F.getInstructionCount();
479*0b57cec5SDimitry Andric   return NumInstrs;
480*0b57cec5SDimitry Andric }
481*0b57cec5SDimitry Andric 
482*0b57cec5SDimitry Andric Comdat *Module::getOrInsertComdat(StringRef Name) {
483*0b57cec5SDimitry Andric   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
484*0b57cec5SDimitry Andric   Entry.second.Name = &Entry;
485*0b57cec5SDimitry Andric   return &Entry.second;
486*0b57cec5SDimitry Andric }
487*0b57cec5SDimitry Andric 
488*0b57cec5SDimitry Andric PICLevel::Level Module::getPICLevel() const {
489*0b57cec5SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
490*0b57cec5SDimitry Andric 
491*0b57cec5SDimitry Andric   if (!Val)
492*0b57cec5SDimitry Andric     return PICLevel::NotPIC;
493*0b57cec5SDimitry Andric 
494*0b57cec5SDimitry Andric   return static_cast<PICLevel::Level>(
495*0b57cec5SDimitry Andric       cast<ConstantInt>(Val->getValue())->getZExtValue());
496*0b57cec5SDimitry Andric }
497*0b57cec5SDimitry Andric 
498*0b57cec5SDimitry Andric void Module::setPICLevel(PICLevel::Level PL) {
499*0b57cec5SDimitry Andric   addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
500*0b57cec5SDimitry Andric }
501*0b57cec5SDimitry Andric 
502*0b57cec5SDimitry Andric PIELevel::Level Module::getPIELevel() const {
503*0b57cec5SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
504*0b57cec5SDimitry Andric 
505*0b57cec5SDimitry Andric   if (!Val)
506*0b57cec5SDimitry Andric     return PIELevel::Default;
507*0b57cec5SDimitry Andric 
508*0b57cec5SDimitry Andric   return static_cast<PIELevel::Level>(
509*0b57cec5SDimitry Andric       cast<ConstantInt>(Val->getValue())->getZExtValue());
510*0b57cec5SDimitry Andric }
511*0b57cec5SDimitry Andric 
512*0b57cec5SDimitry Andric void Module::setPIELevel(PIELevel::Level PL) {
513*0b57cec5SDimitry Andric   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
514*0b57cec5SDimitry Andric }
515*0b57cec5SDimitry Andric 
516*0b57cec5SDimitry Andric Optional<CodeModel::Model> Module::getCodeModel() const {
517*0b57cec5SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
518*0b57cec5SDimitry Andric 
519*0b57cec5SDimitry Andric   if (!Val)
520*0b57cec5SDimitry Andric     return None;
521*0b57cec5SDimitry Andric 
522*0b57cec5SDimitry Andric   return static_cast<CodeModel::Model>(
523*0b57cec5SDimitry Andric       cast<ConstantInt>(Val->getValue())->getZExtValue());
524*0b57cec5SDimitry Andric }
525*0b57cec5SDimitry Andric 
526*0b57cec5SDimitry Andric void Module::setCodeModel(CodeModel::Model CL) {
527*0b57cec5SDimitry Andric   // Linking object files with different code models is undefined behavior
528*0b57cec5SDimitry Andric   // because the compiler would have to generate additional code (to span
529*0b57cec5SDimitry Andric   // longer jumps) if a larger code model is used with a smaller one.
530*0b57cec5SDimitry Andric   // Therefore we will treat attempts to mix code models as an error.
531*0b57cec5SDimitry Andric   addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
532*0b57cec5SDimitry Andric }
533*0b57cec5SDimitry Andric 
534*0b57cec5SDimitry Andric void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
535*0b57cec5SDimitry Andric   if (Kind == ProfileSummary::PSK_CSInstr)
536*0b57cec5SDimitry Andric     addModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
537*0b57cec5SDimitry Andric   else
538*0b57cec5SDimitry Andric     addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
539*0b57cec5SDimitry Andric }
540*0b57cec5SDimitry Andric 
541*0b57cec5SDimitry Andric Metadata *Module::getProfileSummary(bool IsCS) {
542*0b57cec5SDimitry Andric   return (IsCS ? getModuleFlag("CSProfileSummary")
543*0b57cec5SDimitry Andric                : getModuleFlag("ProfileSummary"));
544*0b57cec5SDimitry Andric }
545*0b57cec5SDimitry Andric 
546*0b57cec5SDimitry Andric void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
547*0b57cec5SDimitry Andric   OwnedMemoryBuffer = std::move(MB);
548*0b57cec5SDimitry Andric }
549*0b57cec5SDimitry Andric 
550*0b57cec5SDimitry Andric bool Module::getRtLibUseGOT() const {
551*0b57cec5SDimitry Andric   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
552*0b57cec5SDimitry Andric   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
553*0b57cec5SDimitry Andric }
554*0b57cec5SDimitry Andric 
555*0b57cec5SDimitry Andric void Module::setRtLibUseGOT() {
556*0b57cec5SDimitry Andric   addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
557*0b57cec5SDimitry Andric }
558*0b57cec5SDimitry Andric 
559*0b57cec5SDimitry Andric void Module::setSDKVersion(const VersionTuple &V) {
560*0b57cec5SDimitry Andric   SmallVector<unsigned, 3> Entries;
561*0b57cec5SDimitry Andric   Entries.push_back(V.getMajor());
562*0b57cec5SDimitry Andric   if (auto Minor = V.getMinor()) {
563*0b57cec5SDimitry Andric     Entries.push_back(*Minor);
564*0b57cec5SDimitry Andric     if (auto Subminor = V.getSubminor())
565*0b57cec5SDimitry Andric       Entries.push_back(*Subminor);
566*0b57cec5SDimitry Andric     // Ignore the 'build' component as it can't be represented in the object
567*0b57cec5SDimitry Andric     // file.
568*0b57cec5SDimitry Andric   }
569*0b57cec5SDimitry Andric   addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
570*0b57cec5SDimitry Andric                 ConstantDataArray::get(Context, Entries));
571*0b57cec5SDimitry Andric }
572*0b57cec5SDimitry Andric 
573*0b57cec5SDimitry Andric VersionTuple Module::getSDKVersion() const {
574*0b57cec5SDimitry Andric   auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
575*0b57cec5SDimitry Andric   if (!CM)
576*0b57cec5SDimitry Andric     return {};
577*0b57cec5SDimitry Andric   auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
578*0b57cec5SDimitry Andric   if (!Arr)
579*0b57cec5SDimitry Andric     return {};
580*0b57cec5SDimitry Andric   auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
581*0b57cec5SDimitry Andric     if (Index >= Arr->getNumElements())
582*0b57cec5SDimitry Andric       return None;
583*0b57cec5SDimitry Andric     return (unsigned)Arr->getElementAsInteger(Index);
584*0b57cec5SDimitry Andric   };
585*0b57cec5SDimitry Andric   auto Major = getVersionComponent(0);
586*0b57cec5SDimitry Andric   if (!Major)
587*0b57cec5SDimitry Andric     return {};
588*0b57cec5SDimitry Andric   VersionTuple Result = VersionTuple(*Major);
589*0b57cec5SDimitry Andric   if (auto Minor = getVersionComponent(1)) {
590*0b57cec5SDimitry Andric     Result = VersionTuple(*Major, *Minor);
591*0b57cec5SDimitry Andric     if (auto Subminor = getVersionComponent(2)) {
592*0b57cec5SDimitry Andric       Result = VersionTuple(*Major, *Minor, *Subminor);
593*0b57cec5SDimitry Andric     }
594*0b57cec5SDimitry Andric   }
595*0b57cec5SDimitry Andric   return Result;
596*0b57cec5SDimitry Andric }
597*0b57cec5SDimitry Andric 
598*0b57cec5SDimitry Andric GlobalVariable *llvm::collectUsedGlobalVariables(
599*0b57cec5SDimitry Andric     const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
600*0b57cec5SDimitry Andric   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
601*0b57cec5SDimitry Andric   GlobalVariable *GV = M.getGlobalVariable(Name);
602*0b57cec5SDimitry Andric   if (!GV || !GV->hasInitializer())
603*0b57cec5SDimitry Andric     return GV;
604*0b57cec5SDimitry Andric 
605*0b57cec5SDimitry Andric   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
606*0b57cec5SDimitry Andric   for (Value *Op : Init->operands()) {
607*0b57cec5SDimitry Andric     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
608*0b57cec5SDimitry Andric     Set.insert(G);
609*0b57cec5SDimitry Andric   }
610*0b57cec5SDimitry Andric   return GV;
611*0b57cec5SDimitry Andric }
612