1//===- Module.cpp - Implement the Module class ----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Module class for the IR library.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Module.h"
14#include "SymbolTableListTraitsImpl.h"
15#include "llvm/ADT/SmallString.h"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/IR/Attributes.h"
21#include "llvm/IR/Comdat.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DebugInfoMetadata.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/GVMaterializer.h"
28#include "llvm/IR/GlobalAlias.h"
29#include "llvm/IR/GlobalIFunc.h"
30#include "llvm/IR/GlobalValue.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Metadata.h"
34#include "llvm/IR/ModuleSummaryIndex.h"
35#include "llvm/IR/SymbolTableListTraits.h"
36#include "llvm/IR/Type.h"
37#include "llvm/IR/TypeFinder.h"
38#include "llvm/IR/Value.h"
39#include "llvm/IR/ValueSymbolTable.h"
40#include "llvm/Support/Casting.h"
41#include "llvm/Support/CodeGen.h"
42#include "llvm/Support/Compiler.h"
43#include "llvm/Support/Error.h"
44#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/Support/Path.h"
46#include "llvm/Support/RandomNumberGenerator.h"
47#include "llvm/Support/TimeProfiler.h"
48#include "llvm/Support/VersionTuple.h"
49#include <cassert>
50#include <cstdint>
51#include <memory>
52#include <optional>
53#include <utility>
54#include <vector>
55
56using namespace llvm;
57
58//===----------------------------------------------------------------------===//
59// Methods to implement the globals and functions lists.
60//
61
62// Explicit instantiations of SymbolTableListTraits since some of the methods
63// are not in the public header file.
64template class LLVM_EXPORT_TEMPLATE llvm::SymbolTableListTraits<Function>;
65template class LLVM_EXPORT_TEMPLATE llvm::SymbolTableListTraits<GlobalVariable>;
66template class LLVM_EXPORT_TEMPLATE llvm::SymbolTableListTraits<GlobalAlias>;
67template class LLVM_EXPORT_TEMPLATE llvm::SymbolTableListTraits<GlobalIFunc>;
68
69//===----------------------------------------------------------------------===//
70// Primitive Module methods.
71//
72
73Module::Module(StringRef MID, LLVMContext &C)
74 : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>(args: -1)),
75 ModuleID(std::string(MID)), SourceFileName(std::string(MID)) {
76 Context.addModule(this);
77}
78
79Module &Module::operator=(Module &&Other) {
80 assert(&Context == &Other.Context && "Module must be in the same Context");
81
82 dropAllReferences();
83
84 ModuleID = std::move(Other.ModuleID);
85 SourceFileName = std::move(Other.SourceFileName);
86
87 GlobalList.clear();
88 GlobalList.splice(where: GlobalList.begin(), L2&: Other.GlobalList);
89
90 FunctionList.clear();
91 FunctionList.splice(where: FunctionList.begin(), L2&: Other.FunctionList);
92
93 AliasList.clear();
94 AliasList.splice(where: AliasList.begin(), L2&: Other.AliasList);
95
96 IFuncList.clear();
97 IFuncList.splice(where: IFuncList.begin(), L2&: Other.IFuncList);
98
99 NamedMDList.clear();
100 NamedMDList.splice(where: NamedMDList.begin(), L2&: Other.NamedMDList);
101 for (NamedMDNode &NMD : NamedMDList)
102 NMD.setParent(this);
103
104 NamedMDSymTab = std::move(Other.NamedMDSymTab);
105 ComdatSymTab = std::move(Other.ComdatSymTab);
106 GlobalScopeAsm = std::move(Other.GlobalScopeAsm);
107 OwnedMemoryBuffer = std::move(Other.OwnedMemoryBuffer);
108 Materializer = std::move(Other.Materializer);
109 TargetTriple = std::move(Other.TargetTriple);
110 DL = std::move(Other.DL);
111 CurrentIntrinsicIds = std::move(Other.CurrentIntrinsicIds);
112 UniquedIntrinsicNames = std::move(Other.UniquedIntrinsicNames);
113 ModuleFlags = std::move(Other.ModuleFlags);
114 Context.addModule(this);
115 return *this;
116}
117
118Module::~Module() {
119 Context.removeModule(this);
120 dropAllReferences();
121 GlobalList.clear();
122 FunctionList.clear();
123 AliasList.clear();
124 IFuncList.clear();
125}
126
127void Module::removeDebugIntrinsicDeclarations() {
128 if (auto *DeclareIntrinsicFn =
129 Intrinsic::getDeclarationIfExists(M: this, id: Intrinsic::dbg_declare)) {
130 assert((!isMaterialized() || DeclareIntrinsicFn->hasZeroLiveUses()) &&
131 "Debug declare intrinsic should have had uses removed.");
132 DeclareIntrinsicFn->eraseFromParent();
133 }
134 if (auto *ValueIntrinsicFn =
135 Intrinsic::getDeclarationIfExists(M: this, id: Intrinsic::dbg_value)) {
136 assert((!isMaterialized() || ValueIntrinsicFn->hasZeroLiveUses()) &&
137 "Debug value intrinsic should have had uses removed.");
138 ValueIntrinsicFn->eraseFromParent();
139 }
140 if (auto *AssignIntrinsicFn =
141 Intrinsic::getDeclarationIfExists(M: this, id: Intrinsic::dbg_assign)) {
142 assert((!isMaterialized() || AssignIntrinsicFn->hasZeroLiveUses()) &&
143 "Debug assign intrinsic should have had uses removed.");
144 AssignIntrinsicFn->eraseFromParent();
145 }
146 if (auto *LabelntrinsicFn =
147 Intrinsic::getDeclarationIfExists(M: this, id: Intrinsic::dbg_label)) {
148 assert((!isMaterialized() || LabelntrinsicFn->hasZeroLiveUses()) &&
149 "Debug label intrinsic should have had uses removed.");
150 LabelntrinsicFn->eraseFromParent();
151 }
152}
153
154std::unique_ptr<RandomNumberGenerator>
155Module::createRNG(const StringRef Name) const {
156 SmallString<32> Salt(Name);
157
158 // This RNG is guaranteed to produce the same random stream only
159 // when the Module ID and thus the input filename is the same. This
160 // might be problematic if the input filename extension changes
161 // (e.g. from .c to .bc or .ll).
162 //
163 // We could store this salt in NamedMetadata, but this would make
164 // the parameter non-const. This would unfortunately make this
165 // interface unusable by any Machine passes, since they only have a
166 // const reference to their IR Module. Alternatively we can always
167 // store salt metadata from the Module constructor.
168 Salt += sys::path::filename(path: getModuleIdentifier());
169
170 return std::unique_ptr<RandomNumberGenerator>(
171 new RandomNumberGenerator(Salt));
172}
173
174/// getNamedValue - Return the first global value in the module with
175/// the specified name, of arbitrary type. This method returns null
176/// if a global with the specified name is not found.
177GlobalValue *Module::getNamedValue(StringRef Name) const {
178 return cast_or_null<GlobalValue>(Val: getValueSymbolTable().lookup(Name));
179}
180
181unsigned Module::getNumNamedValues() const {
182 return getValueSymbolTable().size();
183}
184
185/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
186/// This ID is uniqued across modules in the current LLVMContext.
187unsigned Module::getMDKindID(StringRef Name) const {
188 return Context.getMDKindID(Name);
189}
190
191/// getMDKindNames - Populate client supplied SmallVector with the name for
192/// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
193/// so it is filled in as an empty string.
194void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
195 return Context.getMDKindNames(Result);
196}
197
198void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
199 return Context.getOperandBundleTags(Result);
200}
201
202//===----------------------------------------------------------------------===//
203// Methods for easy access to the functions in the module.
204//
205
206// getOrInsertFunction - Look up the specified function in the module symbol
207// table. If it does not exist, add a prototype for the function and return
208// it. This is nice because it allows most passes to get away with not handling
209// the symbol table directly for this common task.
210//
211FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
212 AttributeList AttributeList) {
213 // See if we have a definition for the specified function already.
214 GlobalValue *F = getNamedValue(Name);
215 if (!F) {
216 // Nope, add it
217 Function *New = Function::Create(Ty, Linkage: GlobalVariable::ExternalLinkage,
218 AddrSpace: DL.getProgramAddressSpace(), N: Name, M: this);
219 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
220 New->setAttributes(AttributeList);
221 return {Ty, New}; // Return the new prototype.
222 }
223
224 // Otherwise, we just found the existing function or a prototype.
225 return {Ty, F};
226}
227
228FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
229 return getOrInsertFunction(Name, Ty, AttributeList: AttributeList());
230}
231
232// getFunction - Look up the specified function in the module symbol table.
233// If it does not exist, return null.
234//
235Function *Module::getFunction(StringRef Name) const {
236 return dyn_cast_or_null<Function>(Val: getNamedValue(Name));
237}
238
239//===----------------------------------------------------------------------===//
240// Methods for easy access to the global variables in the module.
241//
242
243/// getGlobalVariable - Look up the specified global variable in the module
244/// symbol table. If it does not exist, return null. The type argument
245/// should be the underlying type of the global, i.e., it should not have
246/// the top-level PointerType, which represents the address of the global.
247/// If AllowLocal is set to true, this function will return types that
248/// have an local. By default, these types are not returned.
249///
250GlobalVariable *Module::getGlobalVariable(StringRef Name,
251 bool AllowLocal) const {
252 if (GlobalVariable *Result =
253 dyn_cast_or_null<GlobalVariable>(Val: getNamedValue(Name)))
254 if (AllowLocal || !Result->hasLocalLinkage())
255 return Result;
256 return nullptr;
257}
258
259/// getOrInsertGlobal - Look up the specified global in the module symbol table.
260/// If it does not exist, add a declaration of the global and return it.
261/// Otherwise, return the existing global.
262GlobalVariable *Module::getOrInsertGlobal(
263 StringRef Name, Type *Ty,
264 function_ref<GlobalVariable *()> CreateGlobalCallback) {
265 // See if we have a definition for the specified global already.
266 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(Val: getNamedValue(Name));
267 if (!GV)
268 GV = CreateGlobalCallback();
269 assert(GV && "The CreateGlobalCallback is expected to create a global");
270
271 // Otherwise, we just found the existing function or a prototype.
272 return GV;
273}
274
275// Overload to construct a global variable using its constructor's defaults.
276GlobalVariable *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
277 return getOrInsertGlobal(Name, Ty, CreateGlobalCallback: [&] {
278 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
279 nullptr, Name);
280 });
281}
282
283//===----------------------------------------------------------------------===//
284// Methods for easy access to the global variables in the module.
285//
286
287// getNamedAlias - Look up the specified global in the module symbol table.
288// If it does not exist, return null.
289//
290GlobalAlias *Module::getNamedAlias(StringRef Name) const {
291 return dyn_cast_or_null<GlobalAlias>(Val: getNamedValue(Name));
292}
293
294GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
295 return dyn_cast_or_null<GlobalIFunc>(Val: getNamedValue(Name));
296}
297
298/// getNamedMetadata - Return the first NamedMDNode in the module with the
299/// specified name. This method returns null if a NamedMDNode with the
300/// specified name is not found.
301NamedMDNode *Module::getNamedMetadata(StringRef Name) const {
302 return NamedMDSymTab.lookup(Key: Name);
303}
304
305/// getOrInsertNamedMetadata - Return the first named MDNode in the module
306/// with the specified name. This method returns a new NamedMDNode if a
307/// NamedMDNode with the specified name is not found.
308NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
309 NamedMDNode *&NMD = NamedMDSymTab[Name];
310 if (!NMD) {
311 NMD = new NamedMDNode(Name);
312 NMD->setParent(this);
313 insertNamedMDNode(MDNode: NMD);
314 if (Name == "llvm.module.flags")
315 ModuleFlags = NMD;
316 }
317 return NMD;
318}
319
320/// eraseNamedMetadata - Remove the given NamedMDNode from this module and
321/// delete it.
322void Module::eraseNamedMetadata(NamedMDNode *NMD) {
323 NamedMDSymTab.erase(Key: NMD->getName());
324 if (NMD == ModuleFlags)
325 ModuleFlags = nullptr;
326 eraseNamedMDNode(MDNode: NMD);
327}
328
329bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
330 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
331 uint64_t Val = Behavior->getLimitedValue();
332 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
333 MFB = static_cast<ModFlagBehavior>(Val);
334 return true;
335 }
336 }
337 return false;
338}
339
340/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
341void Module::
342getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
343 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
344 if (!ModFlags) return;
345
346 for (const MDNode *Flag : ModFlags->operands()) {
347 // The verifier will catch errors, so no need to check them here.
348 auto *MFBConstant = mdconst::extract<ConstantInt>(MD: Flag->getOperand(I: 0));
349 auto MFB = static_cast<ModFlagBehavior>(MFBConstant->getLimitedValue());
350 MDString *Key = cast<MDString>(Val: Flag->getOperand(I: 1));
351 Metadata *Val = Flag->getOperand(I: 2);
352 Flags.push_back(Elt: ModuleFlagEntry(MFB, Key, Val));
353 }
354}
355
356/// Return the corresponding value if Key appears in module flags, otherwise
357/// return null.
358Metadata *Module::getModuleFlag(StringRef Key) const {
359 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
360 if (!ModFlags)
361 return nullptr;
362 for (const MDNode *Flag : ModFlags->operands()) {
363 if (Key == cast<MDString>(Val: Flag->getOperand(I: 1))->getString())
364 return Flag->getOperand(I: 2);
365 }
366 return nullptr;
367}
368
369/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
370/// represents module-level flags. If module-level flags aren't found, it
371/// creates the named metadata that contains them.
372NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
373 if (ModuleFlags)
374 return ModuleFlags;
375 return getOrInsertNamedMetadata(Name: "llvm.module.flags");
376}
377
378/// addModuleFlag - Add a module-level flag to the module-level flags
379/// metadata. It will create the module-level flags named metadata if it doesn't
380/// already exist.
381void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
382 Metadata *Val) {
383 Type *Int32Ty = Type::getInt32Ty(C&: Context);
384 Metadata *Ops[3] = {
385 ConstantAsMetadata::get(C: ConstantInt::get(Ty: Int32Ty, V: Behavior)),
386 MDString::get(Context, Str: Key), Val};
387 getOrInsertModuleFlagsMetadata()->addOperand(M: MDNode::get(Context, MDs: Ops));
388}
389void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
390 Constant *Val) {
391 addModuleFlag(Behavior, Key, Val: ConstantAsMetadata::get(C: Val));
392}
393void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
394 uint32_t Val) {
395 Type *Int32Ty = Type::getInt32Ty(C&: Context);
396 addModuleFlag(Behavior, Key, Val: ConstantInt::get(Ty: Int32Ty, V: Val));
397}
398void Module::addModuleFlag(MDNode *Node) {
399 assert(Node->getNumOperands() == 3 &&
400 "Invalid number of operands for module flag!");
401 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
402 isa<MDString>(Node->getOperand(1)) &&
403 "Invalid operand types for module flag!");
404 getOrInsertModuleFlagsMetadata()->addOperand(M: Node);
405}
406
407void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
408 Metadata *Val) {
409 NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
410 // Replace the flag if it already exists.
411 for (unsigned i = 0; i < ModFlags->getNumOperands(); ++i) {
412 MDNode *Flag = ModFlags->getOperand(i);
413 if (cast<MDString>(Val: Flag->getOperand(I: 1))->getString() == Key) {
414 Type *Int32Ty = Type::getInt32Ty(C&: Context);
415 Metadata *Ops[3] = {
416 ConstantAsMetadata::get(C: ConstantInt::get(Ty: Int32Ty, V: Behavior)),
417 MDString::get(Context, Str: Key), Val};
418 ModFlags->setOperand(I: i, New: MDNode::get(Context, MDs: Ops));
419 return;
420 }
421 }
422 addModuleFlag(Behavior, Key, Val);
423}
424void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
425 Constant *Val) {
426 setModuleFlag(Behavior, Key, Val: ConstantAsMetadata::get(C: Val));
427}
428void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
429 uint32_t Val) {
430 Type *Int32Ty = Type::getInt32Ty(C&: Context);
431 setModuleFlag(Behavior, Key, Val: ConstantInt::get(Ty: Int32Ty, V: Val));
432}
433
434void Module::setDataLayout(StringRef Desc) { DL = DataLayout(Desc); }
435
436void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
437
438DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
439 return cast<DICompileUnit>(Val: CUs->getOperand(i: Idx));
440}
441DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
442 return cast<DICompileUnit>(Val: CUs->getOperand(i: Idx));
443}
444
445void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
446 while (CUs && (Idx < CUs->getNumOperands()) &&
447 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
448 ++Idx;
449}
450
451iterator_range<Module::global_object_iterator> Module::global_objects() {
452 return concat<GlobalObject>(Ranges: functions(), Ranges: globals());
453}
454iterator_range<Module::const_global_object_iterator>
455Module::global_objects() const {
456 return concat<const GlobalObject>(Ranges: functions(), Ranges: globals());
457}
458
459iterator_range<Module::global_value_iterator> Module::global_values() {
460 return concat<GlobalValue>(Ranges: functions(), Ranges: globals(), Ranges: aliases(), Ranges: ifuncs());
461}
462iterator_range<Module::const_global_value_iterator>
463Module::global_values() const {
464 return concat<const GlobalValue>(Ranges: functions(), Ranges: globals(), Ranges: aliases(), Ranges: ifuncs());
465}
466
467//===----------------------------------------------------------------------===//
468// Methods to control the materialization of GlobalValues in the Module.
469//
470void Module::setMaterializer(GVMaterializer *GVM) {
471 assert(!Materializer &&
472 "Module already has a GVMaterializer. Call materializeAll"
473 " to clear it out before setting another one.");
474 Materializer.reset(p: GVM);
475}
476
477Error Module::materialize(GlobalValue *GV) {
478 if (!Materializer)
479 return Error::success();
480
481 return Materializer->materialize(GV);
482}
483
484Error Module::materializeAll() {
485 if (!Materializer)
486 return Error::success();
487 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
488 return M->materializeModule();
489}
490
491Error Module::materializeMetadata() {
492 llvm::TimeTraceScope timeScope("Materialize metadata");
493 if (!Materializer)
494 return Error::success();
495 return Materializer->materializeMetadata();
496}
497
498//===----------------------------------------------------------------------===//
499// Other module related stuff.
500//
501
502std::vector<StructType *> Module::getIdentifiedStructTypes() const {
503 // If we have a materializer, it is possible that some unread function
504 // uses a type that is currently not visible to a TypeFinder, so ask
505 // the materializer which types it created.
506 if (Materializer)
507 return Materializer->getIdentifiedStructTypes();
508
509 std::vector<StructType *> Ret;
510 TypeFinder SrcStructTypes;
511 SrcStructTypes.run(M: *this, onlyNamed: true);
512 Ret.assign(first: SrcStructTypes.begin(), last: SrcStructTypes.end());
513 return Ret;
514}
515
516std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
517 const FunctionType *Proto) {
518 auto Encode = [&BaseName](unsigned Suffix) {
519 return (Twine(BaseName) + "." + Twine(Suffix)).str();
520 };
521
522 {
523 // fast path - the prototype is already known
524 auto UinItInserted = UniquedIntrinsicNames.insert(KV: {{Id, Proto}, 0});
525 if (!UinItInserted.second)
526 return Encode(UinItInserted.first->second);
527 }
528
529 // Not known yet. A new entry was created with index 0. Check if there already
530 // exists a matching declaration, or select a new entry.
531
532 // Start looking for names with the current known maximum count (or 0).
533 auto NiidItInserted = CurrentIntrinsicIds.insert(KV: {BaseName, 0});
534 unsigned Count = NiidItInserted.first->second;
535
536 // This might be slow if a whole population of intrinsics already existed, but
537 // we cache the values for later usage.
538 std::string NewName;
539 while (true) {
540 NewName = Encode(Count);
541 GlobalValue *F = getNamedValue(Name: NewName);
542 if (!F) {
543 // Reserve this entry for the new proto
544 UniquedIntrinsicNames[{Id, Proto}] = Count;
545 break;
546 }
547
548 // A declaration with this name already exists. Remember it.
549 FunctionType *FT = dyn_cast<FunctionType>(Val: F->getValueType());
550 auto UinItInserted = UniquedIntrinsicNames.insert(KV: {{Id, FT}, Count});
551 if (FT == Proto) {
552 // It was a declaration for our prototype. This entry was allocated in the
553 // beginning. Update the count to match the existing declaration.
554 UinItInserted.first->second = Count;
555 break;
556 }
557
558 ++Count;
559 }
560
561 NiidItInserted.first->second = Count + 1;
562
563 return NewName;
564}
565
566// dropAllReferences() - This function causes all the subelements to "let go"
567// of all references that they are maintaining. This allows one to 'delete' a
568// whole module at a time, even though there may be circular references... first
569// all references are dropped, and all use counts go to zero. Then everything
570// is deleted for real. Note that no operations are valid on an object that
571// has "dropped all references", except operator delete.
572//
573void Module::dropAllReferences() {
574 for (Function &F : *this)
575 F.dropAllReferences();
576
577 for (GlobalVariable &GV : globals())
578 GV.dropAllReferences();
579
580 for (GlobalAlias &GA : aliases())
581 GA.dropAllReferences();
582
583 for (GlobalIFunc &GIF : ifuncs())
584 GIF.dropAllReferences();
585}
586
587unsigned Module::getNumberRegisterParameters() const {
588 auto *Val =
589 cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "NumRegisterParameters"));
590 if (!Val)
591 return 0;
592 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue();
593}
594
595unsigned Module::getDwarfVersion() const {
596 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "Dwarf Version"));
597 if (!Val)
598 return 0;
599 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue();
600}
601
602bool Module::isDwarf64() const {
603 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "DWARF64"));
604 return Val && cast<ConstantInt>(Val: Val->getValue())->isOne();
605}
606
607unsigned Module::getCodeViewFlag() const {
608 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "CodeView"));
609 if (!Val)
610 return 0;
611 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue();
612}
613
614unsigned Module::getInstructionCount() const {
615 unsigned NumInstrs = 0;
616 for (const Function &F : FunctionList)
617 NumInstrs += F.getInstructionCount();
618 return NumInstrs;
619}
620
621Comdat *Module::getOrInsertComdat(StringRef Name) {
622 auto &Entry = *ComdatSymTab.insert(KV: std::make_pair(x&: Name, y: Comdat())).first;
623 Entry.second.Name = &Entry;
624 return &Entry.second;
625}
626
627PICLevel::Level Module::getPICLevel() const {
628 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "PIC Level"));
629
630 if (!Val)
631 return PICLevel::NotPIC;
632
633 return static_cast<PICLevel::Level>(
634 cast<ConstantInt>(Val: Val->getValue())->getZExtValue());
635}
636
637void Module::setPICLevel(PICLevel::Level PL) {
638 // The merge result of a non-PIC object and a PIC object can only be reliably
639 // used as a non-PIC object, so use the Min merge behavior.
640 addModuleFlag(Behavior: ModFlagBehavior::Min, Key: "PIC Level", Val: PL);
641}
642
643PIELevel::Level Module::getPIELevel() const {
644 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "PIE Level"));
645
646 if (!Val)
647 return PIELevel::Default;
648
649 return static_cast<PIELevel::Level>(
650 cast<ConstantInt>(Val: Val->getValue())->getZExtValue());
651}
652
653void Module::setPIELevel(PIELevel::Level PL) {
654 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "PIE Level", Val: PL);
655}
656
657std::optional<CodeModel::Model> Module::getCodeModel() const {
658 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "Code Model"));
659
660 if (!Val)
661 return std::nullopt;
662
663 return static_cast<CodeModel::Model>(
664 cast<ConstantInt>(Val: Val->getValue())->getZExtValue());
665}
666
667void Module::setCodeModel(CodeModel::Model CL) {
668 // Linking object files with different code models is undefined behavior
669 // because the compiler would have to generate additional code (to span
670 // longer jumps) if a larger code model is used with a smaller one.
671 // Therefore we will treat attempts to mix code models as an error.
672 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "Code Model", Val: CL);
673}
674
675std::optional<uint64_t> Module::getLargeDataThreshold() const {
676 auto *Val =
677 cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "Large Data Threshold"));
678
679 if (!Val)
680 return std::nullopt;
681
682 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue();
683}
684
685void Module::setLargeDataThreshold(uint64_t Threshold) {
686 // Since the large data threshold goes along with the code model, the merge
687 // behavior is the same.
688 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "Large Data Threshold",
689 Val: ConstantInt::get(Ty: Type::getInt64Ty(C&: Context), V: Threshold));
690}
691
692void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
693 if (Kind == ProfileSummary::PSK_CSInstr)
694 setModuleFlag(Behavior: ModFlagBehavior::Error, Key: "CSProfileSummary", Val: M);
695 else
696 setModuleFlag(Behavior: ModFlagBehavior::Error, Key: "ProfileSummary", Val: M);
697}
698
699Metadata *Module::getProfileSummary(bool IsCS) const {
700 return (IsCS ? getModuleFlag(Key: "CSProfileSummary")
701 : getModuleFlag(Key: "ProfileSummary"));
702}
703
704bool Module::getSemanticInterposition() const {
705 Metadata *MF = getModuleFlag(Key: "SemanticInterposition");
706
707 auto *Val = cast_or_null<ConstantAsMetadata>(Val: MF);
708 if (!Val)
709 return false;
710
711 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue();
712}
713
714void Module::setSemanticInterposition(bool SI) {
715 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "SemanticInterposition", Val: SI);
716}
717
718void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
719 OwnedMemoryBuffer = std::move(MB);
720}
721
722bool Module::getRtLibUseGOT() const {
723 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "RtLibUseGOT"));
724 return Val && (cast<ConstantInt>(Val: Val->getValue())->getZExtValue() > 0);
725}
726
727void Module::setRtLibUseGOT() {
728 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "RtLibUseGOT", Val: 1);
729}
730
731bool Module::getDirectAccessExternalData() const {
732 auto *Val = cast_or_null<ConstantAsMetadata>(
733 Val: getModuleFlag(Key: "direct-access-external-data"));
734 if (Val)
735 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue() > 0;
736 return getPICLevel() == PICLevel::NotPIC;
737}
738
739void Module::setDirectAccessExternalData(bool Value) {
740 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "direct-access-external-data", Val: Value);
741}
742
743UWTableKind Module::getUwtable() const {
744 if (auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "uwtable")))
745 return UWTableKind(cast<ConstantInt>(Val: Val->getValue())->getZExtValue());
746 return UWTableKind::None;
747}
748
749void Module::setUwtable(UWTableKind Kind) {
750 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "uwtable", Val: uint32_t(Kind));
751}
752
753FramePointerKind Module::getFramePointer() const {
754 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "frame-pointer"));
755 return static_cast<FramePointerKind>(
756 Val ? cast<ConstantInt>(Val: Val->getValue())->getZExtValue() : 0);
757}
758
759void Module::setFramePointer(FramePointerKind Kind) {
760 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "frame-pointer", Val: static_cast<int>(Kind));
761}
762
763StringRef Module::getStackProtectorGuard() const {
764 Metadata *MD = getModuleFlag(Key: "stack-protector-guard");
765 if (auto *MDS = dyn_cast_or_null<MDString>(Val: MD))
766 return MDS->getString();
767 return {};
768}
769
770void Module::setStackProtectorGuard(StringRef Kind) {
771 MDString *ID = MDString::get(Context&: getContext(), Str: Kind);
772 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "stack-protector-guard", Val: ID);
773}
774
775StringRef Module::getStackProtectorGuardReg() const {
776 Metadata *MD = getModuleFlag(Key: "stack-protector-guard-reg");
777 if (auto *MDS = dyn_cast_or_null<MDString>(Val: MD))
778 return MDS->getString();
779 return {};
780}
781
782void Module::setStackProtectorGuardReg(StringRef Reg) {
783 MDString *ID = MDString::get(Context&: getContext(), Str: Reg);
784 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "stack-protector-guard-reg", Val: ID);
785}
786
787StringRef Module::getStackProtectorGuardSymbol() const {
788 Metadata *MD = getModuleFlag(Key: "stack-protector-guard-symbol");
789 if (auto *MDS = dyn_cast_or_null<MDString>(Val: MD))
790 return MDS->getString();
791 return {};
792}
793
794void Module::setStackProtectorGuardSymbol(StringRef Symbol) {
795 MDString *ID = MDString::get(Context&: getContext(), Str: Symbol);
796 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "stack-protector-guard-symbol", Val: ID);
797}
798
799int Module::getStackProtectorGuardOffset() const {
800 Metadata *MD = getModuleFlag(Key: "stack-protector-guard-offset");
801 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
802 return CI->getSExtValue();
803 return INT_MAX;
804}
805
806void Module::setStackProtectorGuardOffset(int Offset) {
807 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "stack-protector-guard-offset", Val: Offset);
808}
809
810unsigned Module::getOverrideStackAlignment() const {
811 Metadata *MD = getModuleFlag(Key: "override-stack-alignment");
812 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
813 return CI->getZExtValue();
814 return 0;
815}
816
817unsigned Module::getMaxTLSAlignment() const {
818 Metadata *MD = getModuleFlag(Key: "MaxTLSAlign");
819 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
820 return CI->getZExtValue();
821 return 0;
822}
823
824void Module::setOverrideStackAlignment(unsigned Align) {
825 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "override-stack-alignment", Val: Align);
826}
827
828static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name) {
829 SmallVector<unsigned, 3> Entries;
830 Entries.push_back(Elt: V.getMajor());
831 if (auto Minor = V.getMinor()) {
832 Entries.push_back(Elt: *Minor);
833 if (auto Subminor = V.getSubminor())
834 Entries.push_back(Elt: *Subminor);
835 // Ignore the 'build' component as it can't be represented in the object
836 // file.
837 }
838 M.addModuleFlag(Behavior: Module::ModFlagBehavior::Warning, Key: Name,
839 Val: ConstantDataArray::get(Context&: M.getContext(), Elts&: Entries));
840}
841
842void Module::setSDKVersion(const VersionTuple &V) {
843 addSDKVersionMD(V, M&: *this, Name: "SDK Version");
844}
845
846static VersionTuple getSDKVersionMD(Metadata *MD) {
847 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(Val: MD);
848 if (!CM)
849 return {};
850 auto *Arr = dyn_cast_or_null<ConstantDataArray>(Val: CM->getValue());
851 if (!Arr)
852 return {};
853 auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> {
854 if (Index >= Arr->getNumElements())
855 return std::nullopt;
856 return (unsigned)Arr->getElementAsInteger(i: Index);
857 };
858 auto Major = getVersionComponent(0);
859 if (!Major)
860 return {};
861 VersionTuple Result = VersionTuple(*Major);
862 if (auto Minor = getVersionComponent(1)) {
863 Result = VersionTuple(*Major, *Minor);
864 if (auto Subminor = getVersionComponent(2)) {
865 Result = VersionTuple(*Major, *Minor, *Subminor);
866 }
867 }
868 return Result;
869}
870
871VersionTuple Module::getSDKVersion() const {
872 return getSDKVersionMD(MD: getModuleFlag(Key: "SDK Version"));
873}
874
875GlobalVariable *llvm::collectUsedGlobalVariables(
876 const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
877 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
878 GlobalVariable *GV = M.getGlobalVariable(Name);
879 if (!GV || !GV->hasInitializer())
880 return GV;
881
882 const ConstantArray *Init = cast<ConstantArray>(Val: GV->getInitializer());
883 for (Value *Op : Init->operands()) {
884 GlobalValue *G = cast<GlobalValue>(Val: Op->stripPointerCasts());
885 Vec.push_back(Elt: G);
886 }
887 return GV;
888}
889
890void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) {
891 if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
892 std::unique_ptr<ProfileSummary> ProfileSummary(
893 ProfileSummary::getFromMD(MD: SummaryMD));
894 if (ProfileSummary) {
895 if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample ||
896 !ProfileSummary->isPartialProfile())
897 return;
898 uint64_t BlockCount = Index.getBlockCount();
899 uint32_t NumCounts = ProfileSummary->getNumCounts();
900 if (!NumCounts)
901 return;
902 double Ratio = (double)BlockCount / NumCounts;
903 ProfileSummary->setPartialProfileRatio(Ratio);
904 setProfileSummary(M: ProfileSummary->getMD(Context&: getContext()),
905 Kind: ProfileSummary::PSK_Sample);
906 }
907 }
908}
909
910StringRef Module::getDarwinTargetVariantTriple() const {
911 if (const auto *MD = getModuleFlag(Key: "darwin.target_variant.triple"))
912 return cast<MDString>(Val: MD)->getString();
913 return "";
914}
915
916void Module::setDarwinTargetVariantTriple(StringRef T) {
917 addModuleFlag(Behavior: ModFlagBehavior::Warning, Key: "darwin.target_variant.triple",
918 Val: MDString::get(Context&: getContext(), Str: T));
919}
920
921VersionTuple Module::getDarwinTargetVariantSDKVersion() const {
922 return getSDKVersionMD(MD: getModuleFlag(Key: "darwin.target_variant.SDK Version"));
923}
924
925void Module::setDarwinTargetVariantSDKVersion(VersionTuple Version) {
926 addSDKVersionMD(V: Version, M&: *this, Name: "darwin.target_variant.SDK Version");
927}
928
929StringRef Module::getTargetABIFromMD() {
930 StringRef TargetABI;
931 if (auto *TargetABIMD =
932 dyn_cast_or_null<MDString>(Val: getModuleFlag(Key: "target-abi")))
933 TargetABI = TargetABIMD->getString();
934 return TargetABI;
935}
936
937WinX64EHUnwindV2Mode Module::getWinX64EHUnwindV2Mode() const {
938 Metadata *MD = getModuleFlag(Key: "winx64-eh-unwindv2");
939 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
940 return static_cast<WinX64EHUnwindV2Mode>(CI->getZExtValue());
941 return WinX64EHUnwindV2Mode::Disabled;
942}
943
944ControlFlowGuardMode Module::getControlFlowGuardMode() const {
945 Metadata *MD = getModuleFlag(Key: "cfguard");
946 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
947 return static_cast<ControlFlowGuardMode>(CI->getZExtValue());
948 return ControlFlowGuardMode::Disabled;
949}
950