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 uint64_t Val) {
395 Type *Int64Ty = Type::getInt64Ty(C&: Context);
396 addModuleFlag(Behavior, Key, Val: ConstantInt::get(Ty: Int64Ty, V: Val));
397}
398void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
399 uint32_t Val) {
400 Type *Int32Ty = Type::getInt32Ty(C&: Context);
401 addModuleFlag(Behavior, Key, Val: ConstantInt::get(Ty: Int32Ty, V: Val));
402}
403void Module::addModuleFlag(MDNode *Node) {
404 assert(Node->getNumOperands() == 3 &&
405 "Invalid number of operands for module flag!");
406 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
407 isa<MDString>(Node->getOperand(1)) &&
408 "Invalid operand types for module flag!");
409 getOrInsertModuleFlagsMetadata()->addOperand(M: Node);
410}
411
412void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
413 Metadata *Val) {
414 NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
415 // Replace the flag if it already exists.
416 for (unsigned i = 0; i < ModFlags->getNumOperands(); ++i) {
417 MDNode *Flag = ModFlags->getOperand(i);
418 if (cast<MDString>(Val: Flag->getOperand(I: 1))->getString() == Key) {
419 Type *Int32Ty = Type::getInt32Ty(C&: Context);
420 Metadata *Ops[3] = {
421 ConstantAsMetadata::get(C: ConstantInt::get(Ty: Int32Ty, V: Behavior)),
422 MDString::get(Context, Str: Key), Val};
423 ModFlags->setOperand(I: i, New: MDNode::get(Context, MDs: Ops));
424 return;
425 }
426 }
427 addModuleFlag(Behavior, Key, Val);
428}
429void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
430 Constant *Val) {
431 setModuleFlag(Behavior, Key, Val: ConstantAsMetadata::get(C: Val));
432}
433void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
434 uint64_t Val) {
435 Type *Int64Ty = Type::getInt64Ty(C&: Context);
436 setModuleFlag(Behavior, Key, Val: ConstantInt::get(Ty: Int64Ty, V: Val));
437}
438void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
439 uint32_t Val) {
440 Type *Int32Ty = Type::getInt32Ty(C&: Context);
441 setModuleFlag(Behavior, Key, Val: ConstantInt::get(Ty: Int32Ty, V: Val));
442}
443
444void Module::setDataLayout(StringRef Desc) { DL = DataLayout(Desc); }
445
446void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
447
448DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
449 return cast<DICompileUnit>(Val: CUs->getOperand(i: Idx));
450}
451DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
452 return cast<DICompileUnit>(Val: CUs->getOperand(i: Idx));
453}
454
455void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
456 while (CUs && (Idx < CUs->getNumOperands()) &&
457 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
458 ++Idx;
459}
460
461iterator_range<Module::global_object_iterator> Module::global_objects() {
462 return concat<GlobalObject>(Ranges: functions(), Ranges: globals());
463}
464iterator_range<Module::const_global_object_iterator>
465Module::global_objects() const {
466 return concat<const GlobalObject>(Ranges: functions(), Ranges: globals());
467}
468
469iterator_range<Module::global_value_iterator> Module::global_values() {
470 return concat<GlobalValue>(Ranges: functions(), Ranges: globals(), Ranges: aliases(), Ranges: ifuncs());
471}
472iterator_range<Module::const_global_value_iterator>
473Module::global_values() const {
474 return concat<const GlobalValue>(Ranges: functions(), Ranges: globals(), Ranges: aliases(), Ranges: ifuncs());
475}
476
477//===----------------------------------------------------------------------===//
478// Methods to control the materialization of GlobalValues in the Module.
479//
480void Module::setMaterializer(GVMaterializer *GVM) {
481 assert(!Materializer &&
482 "Module already has a GVMaterializer. Call materializeAll"
483 " to clear it out before setting another one.");
484 Materializer.reset(p: GVM);
485}
486
487Error Module::materialize(GlobalValue *GV) {
488 if (!Materializer)
489 return Error::success();
490
491 return Materializer->materialize(GV);
492}
493
494Error Module::materializeAll() {
495 if (!Materializer)
496 return Error::success();
497 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
498 return M->materializeModule();
499}
500
501Error Module::materializeMetadata() {
502 llvm::TimeTraceScope timeScope("Materialize metadata");
503 if (!Materializer)
504 return Error::success();
505 return Materializer->materializeMetadata();
506}
507
508//===----------------------------------------------------------------------===//
509// Other module related stuff.
510//
511
512std::vector<StructType *> Module::getIdentifiedStructTypes() const {
513 // If we have a materializer, it is possible that some unread function
514 // uses a type that is currently not visible to a TypeFinder, so ask
515 // the materializer which types it created.
516 if (Materializer)
517 return Materializer->getIdentifiedStructTypes();
518
519 std::vector<StructType *> Ret;
520 TypeFinder SrcStructTypes;
521 SrcStructTypes.run(M: *this, onlyNamed: true);
522 Ret.assign(first: SrcStructTypes.begin(), last: SrcStructTypes.end());
523 return Ret;
524}
525
526std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
527 const FunctionType *Proto) {
528 auto Encode = [&BaseName](unsigned Suffix) {
529 return (Twine(BaseName) + "." + Twine(Suffix)).str();
530 };
531
532 {
533 // fast path - the prototype is already known
534 auto UinItInserted = UniquedIntrinsicNames.insert(KV: {{Id, Proto}, 0});
535 if (!UinItInserted.second)
536 return Encode(UinItInserted.first->second);
537 }
538
539 // Not known yet. A new entry was created with index 0. Check if there already
540 // exists a matching declaration, or select a new entry.
541
542 // Start looking for names with the current known maximum count (or 0).
543 auto NiidItInserted = CurrentIntrinsicIds.insert(KV: {BaseName, 0});
544 unsigned Count = NiidItInserted.first->second;
545
546 // This might be slow if a whole population of intrinsics already existed, but
547 // we cache the values for later usage.
548 std::string NewName;
549 while (true) {
550 NewName = Encode(Count);
551 GlobalValue *F = getNamedValue(Name: NewName);
552 if (!F) {
553 // Reserve this entry for the new proto
554 UniquedIntrinsicNames[{Id, Proto}] = Count;
555 break;
556 }
557
558 // A declaration with this name already exists. Remember it.
559 FunctionType *FT = dyn_cast<FunctionType>(Val: F->getValueType());
560 auto UinItInserted = UniquedIntrinsicNames.insert(KV: {{Id, FT}, Count});
561 if (FT == Proto) {
562 // It was a declaration for our prototype. This entry was allocated in the
563 // beginning. Update the count to match the existing declaration.
564 UinItInserted.first->second = Count;
565 break;
566 }
567
568 ++Count;
569 }
570
571 NiidItInserted.first->second = Count + 1;
572
573 return NewName;
574}
575
576// dropAllReferences() - This function causes all the subelements to "let go"
577// of all references that they are maintaining. This allows one to 'delete' a
578// whole module at a time, even though there may be circular references... first
579// all references are dropped, and all use counts go to zero. Then everything
580// is deleted for real. Note that no operations are valid on an object that
581// has "dropped all references", except operator delete.
582//
583void Module::dropAllReferences() {
584 for (Function &F : *this)
585 F.dropAllReferences();
586
587 for (GlobalVariable &GV : globals())
588 GV.dropAllReferences();
589
590 for (GlobalAlias &GA : aliases())
591 GA.dropAllReferences();
592
593 for (GlobalIFunc &GIF : ifuncs())
594 GIF.dropAllReferences();
595}
596
597unsigned Module::getNumberRegisterParameters() const {
598 auto *Val =
599 cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "NumRegisterParameters"));
600 if (!Val)
601 return 0;
602 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue();
603}
604
605unsigned Module::getDwarfVersion() const {
606 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "Dwarf Version"));
607 if (!Val)
608 return 0;
609 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue();
610}
611
612bool Module::isDwarf64() const {
613 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "DWARF64"));
614 return Val && cast<ConstantInt>(Val: Val->getValue())->isOne();
615}
616
617unsigned Module::getCodeViewFlag() const {
618 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "CodeView"));
619 if (!Val)
620 return 0;
621 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue();
622}
623
624unsigned Module::getInstructionCount() const {
625 unsigned NumInstrs = 0;
626 for (const Function &F : FunctionList)
627 NumInstrs += F.getInstructionCount();
628 return NumInstrs;
629}
630
631Comdat *Module::getOrInsertComdat(StringRef Name) {
632 auto &Entry = *ComdatSymTab.insert(KV: std::make_pair(x&: Name, y: Comdat())).first;
633 Entry.second.Name = &Entry;
634 return &Entry.second;
635}
636
637PICLevel::Level Module::getPICLevel() const {
638 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "PIC Level"));
639
640 if (!Val)
641 return PICLevel::NotPIC;
642
643 return static_cast<PICLevel::Level>(
644 cast<ConstantInt>(Val: Val->getValue())->getZExtValue());
645}
646
647void Module::setPICLevel(PICLevel::Level PL) {
648 // The merge result of a non-PIC object and a PIC object can only be reliably
649 // used as a non-PIC object, so use the Min merge behavior.
650 addModuleFlag(Behavior: ModFlagBehavior::Min, Key: "PIC Level", Val: PL);
651}
652
653PIELevel::Level Module::getPIELevel() const {
654 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "PIE Level"));
655
656 if (!Val)
657 return PIELevel::Default;
658
659 return static_cast<PIELevel::Level>(
660 cast<ConstantInt>(Val: Val->getValue())->getZExtValue());
661}
662
663void Module::setPIELevel(PIELevel::Level PL) {
664 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "PIE Level", Val: PL);
665}
666
667std::optional<CodeModel::Model> Module::getCodeModel() const {
668 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "Code Model"));
669
670 if (!Val)
671 return std::nullopt;
672
673 return static_cast<CodeModel::Model>(
674 cast<ConstantInt>(Val: Val->getValue())->getZExtValue());
675}
676
677void Module::setCodeModel(CodeModel::Model CL) {
678 // Linking object files with different code models is undefined behavior
679 // because the compiler would have to generate additional code (to span
680 // longer jumps) if a larger code model is used with a smaller one.
681 // Therefore we will treat attempts to mix code models as an error.
682 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "Code Model", Val: CL);
683}
684
685LongDoubleFormat Module::getLongDoubleFormat() const {
686 if (auto *Val =
687 dyn_cast_or_null<MDString>(Val: getModuleFlag(Key: "long-double-type"))) {
688 if (std::optional<LongDoubleFormat> Format =
689 parseLongDoubleFormat(Name: Val->getString()))
690 return *Format;
691 }
692
693 return getTargetTriple().getDefaultLongDoubleFormat();
694}
695
696void Module::setLongDoubleFormat(LongDoubleFormat Format) {
697 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "long-double-type",
698 Val: MDString::get(Context&: getContext(), Str: getLongDoubleFormatName(Format)));
699}
700
701FloatABI::ABIType Module::getFloatABI() const {
702 if (auto *Val = dyn_cast_or_null<MDString>(Val: getModuleFlag(Key: "float-abi")))
703 return *FloatABI::parseABIType(S: Val->getString());
704 // Without an explicit flag, fall back to the ABI implied by the target
705 // triple.
706 return getTargetTriple().getDefaultFloatABI();
707}
708
709ThreadModel Module::getThreadModel() const {
710 if (auto *Val = cast_or_null<MDString>(Val: getModuleFlag(Key: "thread-model")))
711 return *parseThreadModel(S: Val->getString());
712 return getTargetTriple().getDefaultThreadModel();
713}
714
715void Module::setThreadModel(ThreadModel Model) {
716 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "thread-model",
717 Val: MDString::get(Context&: getContext(), Str: getThreadModelName(TM: Model)));
718}
719
720ExceptionHandling Module::getExceptionModel() const {
721 if (auto *Val = dyn_cast_or_null<MDString>(Val: getModuleFlag(Key: "exception-model")))
722 return *parseExceptionModel(Name: Val->getString());
723
724 // TODO: Return getDefaultExceptionHandling when TargetOptions field is
725 // deleted.
726 return ExceptionHandling::Default;
727}
728
729std::optional<uint64_t> Module::getLargeDataThreshold() const {
730 auto *Val =
731 cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "Large Data Threshold"));
732
733 if (!Val)
734 return std::nullopt;
735
736 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue();
737}
738
739void Module::setLargeDataThreshold(uint64_t Threshold) {
740 // Since the large data threshold goes along with the code model, the merge
741 // behavior is the same.
742 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "Large Data Threshold",
743 Val: ConstantInt::get(Ty: Type::getInt64Ty(C&: Context), V: Threshold));
744}
745
746void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
747 if (Kind == ProfileSummary::PSK_CSInstr)
748 setModuleFlag(Behavior: ModFlagBehavior::Error, Key: "CSProfileSummary", Val: M);
749 else
750 setModuleFlag(Behavior: ModFlagBehavior::Error, Key: "ProfileSummary", Val: M);
751}
752
753Metadata *Module::getProfileSummary(bool IsCS) const {
754 return (IsCS ? getModuleFlag(Key: "CSProfileSummary")
755 : getModuleFlag(Key: "ProfileSummary"));
756}
757
758bool Module::getSemanticInterposition() const {
759 Metadata *MF = getModuleFlag(Key: "SemanticInterposition");
760
761 auto *Val = cast_or_null<ConstantAsMetadata>(Val: MF);
762 if (!Val)
763 return false;
764
765 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue();
766}
767
768void Module::setSemanticInterposition(bool SI) {
769 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "SemanticInterposition", Val: SI);
770}
771
772void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
773 OwnedMemoryBuffer = std::move(MB);
774}
775
776bool Module::getRtLibUseGOT() const {
777 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "RtLibUseGOT"));
778 return Val && (cast<ConstantInt>(Val: Val->getValue())->getZExtValue() > 0);
779}
780
781void Module::setRtLibUseGOT() {
782 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "RtLibUseGOT", Val: 1);
783}
784
785bool Module::getDirectAccessExternalData() const {
786 auto *Val = cast_or_null<ConstantAsMetadata>(
787 Val: getModuleFlag(Key: "direct-access-external-data"));
788 if (Val)
789 return cast<ConstantInt>(Val: Val->getValue())->getZExtValue() > 0;
790 return getPICLevel() == PICLevel::NotPIC;
791}
792
793void Module::setDirectAccessExternalData(bool Value) {
794 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "direct-access-external-data", Val: Value);
795}
796
797UWTableKind Module::getUwtable() const {
798 if (auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "uwtable")))
799 return UWTableKind(cast<ConstantInt>(Val: Val->getValue())->getZExtValue());
800 return UWTableKind::None;
801}
802
803void Module::setUwtable(UWTableKind Kind) {
804 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "uwtable", Val: uint32_t(Kind));
805}
806
807FramePointerKind Module::getFramePointer() const {
808 auto *Val = cast_or_null<ConstantAsMetadata>(Val: getModuleFlag(Key: "frame-pointer"));
809 return static_cast<FramePointerKind>(
810 Val ? cast<ConstantInt>(Val: Val->getValue())->getZExtValue() : 0);
811}
812
813void Module::setFramePointer(FramePointerKind Kind) {
814 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "frame-pointer", Val: static_cast<int>(Kind));
815}
816
817bool Module::hasStackProtectorGuardRecord() const {
818 auto *Val = cast_or_null<ConstantAsMetadata>(
819 Val: getModuleFlag(Key: "stack-protector-guard-record"));
820 return Val && cast<ConstantInt>(Val: Val->getValue())->isOne();
821}
822
823void Module::setStackProtectorGuardRecord(bool Flag) {
824 addModuleFlag(Behavior: ModFlagBehavior::Max, Key: "stack-protector-guard-record",
825 Val: Flag ? 1 : 0);
826}
827
828StringRef Module::getStackProtectorGuard() const {
829 Metadata *MD = getModuleFlag(Key: "stack-protector-guard");
830 if (auto *MDS = dyn_cast_or_null<MDString>(Val: MD))
831 return MDS->getString();
832 return {};
833}
834
835void Module::setStackProtectorGuard(StringRef Kind) {
836 MDString *ID = MDString::get(Context&: getContext(), Str: Kind);
837 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "stack-protector-guard", Val: ID);
838}
839
840StringRef Module::getStackProtectorGuardReg() const {
841 Metadata *MD = getModuleFlag(Key: "stack-protector-guard-reg");
842 if (auto *MDS = dyn_cast_or_null<MDString>(Val: MD))
843 return MDS->getString();
844 return {};
845}
846
847void Module::setStackProtectorGuardReg(StringRef Reg) {
848 MDString *ID = MDString::get(Context&: getContext(), Str: Reg);
849 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "stack-protector-guard-reg", Val: ID);
850}
851
852StringRef Module::getStackProtectorGuardSymbol() const {
853 Metadata *MD = getModuleFlag(Key: "stack-protector-guard-symbol");
854 if (auto *MDS = dyn_cast_or_null<MDString>(Val: MD))
855 return MDS->getString();
856 return {};
857}
858
859void Module::setStackProtectorGuardSymbol(StringRef Symbol) {
860 MDString *ID = MDString::get(Context&: getContext(), Str: Symbol);
861 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "stack-protector-guard-symbol", Val: ID);
862}
863
864int Module::getStackProtectorGuardOffset() const {
865 Metadata *MD = getModuleFlag(Key: "stack-protector-guard-offset");
866 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
867 return CI->getSExtValue();
868 return INT_MAX;
869}
870
871void Module::setStackProtectorGuardOffset(int Offset) {
872 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "stack-protector-guard-offset", Val: Offset);
873}
874
875std::optional<unsigned> Module::getStackProtectorGuardValueWidth() const {
876 Metadata *MD = getModuleFlag(Key: "stack-protector-guard-value-width");
877 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
878 return CI->getZExtValue();
879 return std::nullopt;
880}
881
882void Module::setStackProtectorGuardValueWidth(unsigned Width) {
883 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "stack-protector-guard-value-width",
884 Val: Width);
885}
886
887unsigned Module::getOverrideStackAlignment() const {
888 Metadata *MD = getModuleFlag(Key: "override-stack-alignment");
889 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
890 return CI->getZExtValue();
891 return 0;
892}
893
894unsigned Module::getMaxTLSAlignment() const {
895 Metadata *MD = getModuleFlag(Key: "MaxTLSAlign");
896 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
897 return CI->getZExtValue();
898 return 0;
899}
900
901void Module::setOverrideStackAlignment(unsigned Align) {
902 addModuleFlag(Behavior: ModFlagBehavior::Error, Key: "override-stack-alignment", Val: Align);
903}
904
905static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name) {
906 SmallVector<unsigned, 3> Entries;
907 Entries.push_back(Elt: V.getMajor());
908 if (auto Minor = V.getMinor()) {
909 Entries.push_back(Elt: *Minor);
910 if (auto Subminor = V.getSubminor())
911 Entries.push_back(Elt: *Subminor);
912 // Ignore the 'build' component as it can't be represented in the object
913 // file.
914 }
915 M.addModuleFlag(Behavior: Module::ModFlagBehavior::Warning, Key: Name,
916 Val: ConstantDataArray::get(Context&: M.getContext(), Elts&: Entries));
917}
918
919void Module::setSDKVersion(const VersionTuple &V) {
920 addSDKVersionMD(V, M&: *this, Name: "SDK Version");
921}
922
923static VersionTuple getSDKVersionMD(Metadata *MD) {
924 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(Val: MD);
925 if (!CM)
926 return {};
927 auto *Arr = dyn_cast_or_null<ConstantDataArray>(Val: CM->getValue());
928 if (!Arr)
929 return {};
930 auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> {
931 if (Index >= Arr->getNumElements())
932 return std::nullopt;
933 return (unsigned)Arr->getElementAsInteger(i: Index);
934 };
935 auto Major = getVersionComponent(0);
936 if (!Major)
937 return {};
938 VersionTuple Result = VersionTuple(*Major);
939 if (auto Minor = getVersionComponent(1)) {
940 Result = VersionTuple(*Major, *Minor);
941 if (auto Subminor = getVersionComponent(2)) {
942 Result = VersionTuple(*Major, *Minor, *Subminor);
943 }
944 }
945 return Result;
946}
947
948VersionTuple Module::getSDKVersion() const {
949 return getSDKVersionMD(MD: getModuleFlag(Key: "SDK Version"));
950}
951
952GlobalVariable *llvm::collectUsedGlobalVariables(
953 const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
954 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
955 GlobalVariable *GV = M.getGlobalVariable(Name);
956 if (!GV || !GV->hasInitializer())
957 return GV;
958
959 const ConstantArray *Init = cast<ConstantArray>(Val: GV->getInitializer());
960 for (Value *Op : Init->operands()) {
961 GlobalValue *G = cast<GlobalValue>(Val: Op->stripPointerCasts());
962 Vec.push_back(Elt: G);
963 }
964 return GV;
965}
966
967void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) {
968 if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
969 std::unique_ptr<ProfileSummary> ProfileSummary(
970 ProfileSummary::getFromMD(MD: SummaryMD));
971 if (ProfileSummary) {
972 if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample ||
973 !ProfileSummary->isPartialProfile())
974 return;
975 uint64_t BlockCount = Index.getBlockCount();
976 uint32_t NumCounts = ProfileSummary->getNumCounts();
977 if (!NumCounts)
978 return;
979 double Ratio = (double)BlockCount / NumCounts;
980 ProfileSummary->setPartialProfileRatio(Ratio);
981 setProfileSummary(M: ProfileSummary->getMD(Context&: getContext()),
982 Kind: ProfileSummary::PSK_Sample);
983 }
984 }
985}
986
987StringRef Module::getDarwinTargetVariantTriple() const {
988 if (const auto *MD = getModuleFlag(Key: "darwin.target_variant.triple"))
989 return cast<MDString>(Val: MD)->getString();
990 return "";
991}
992
993void Module::setDarwinTargetVariantTriple(StringRef T) {
994 addModuleFlag(Behavior: ModFlagBehavior::Warning, Key: "darwin.target_variant.triple",
995 Val: MDString::get(Context&: getContext(), Str: T));
996}
997
998VersionTuple Module::getDarwinTargetVariantSDKVersion() const {
999 return getSDKVersionMD(MD: getModuleFlag(Key: "darwin.target_variant.SDK Version"));
1000}
1001
1002void Module::setDarwinTargetVariantSDKVersion(VersionTuple Version) {
1003 addSDKVersionMD(V: Version, M&: *this, Name: "darwin.target_variant.SDK Version");
1004}
1005
1006StringRef Module::getTargetABIFromMD() {
1007 StringRef TargetABI;
1008 if (auto *TargetABIMD =
1009 dyn_cast_or_null<MDString>(Val: getModuleFlag(Key: "target-abi")))
1010 TargetABI = TargetABIMD->getString();
1011 return TargetABI;
1012}
1013
1014WinX64EHUnwindMode Module::getWinX64EHUnwindMode() const {
1015 // Check the new unified flag first.
1016 if (Metadata *MD = getModuleFlag(Key: "winx64-eh-unwind")) {
1017 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
1018 return static_cast<WinX64EHUnwindMode>(CI->getZExtValue());
1019 }
1020 // Fall back to the legacy V2 flag.
1021 if (Metadata *MD = getModuleFlag(Key: "winx64-eh-unwindv2")) {
1022 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
1023 return static_cast<WinX64EHUnwindMode>(CI->getZExtValue());
1024 }
1025 return WinX64EHUnwindMode::V1;
1026}
1027
1028ControlFlowGuardMode Module::getControlFlowGuardMode() const {
1029 Metadata *MD = getModuleFlag(Key: "cfguard");
1030 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
1031 return static_cast<ControlFlowGuardMode>(CI->getZExtValue());
1032 return ControlFlowGuardMode::Disabled;
1033}
1034
1035bool Module::GlobalAsmProperties::set(StringRef Name, std::string Value) {
1036 if (Name == "target_features")
1037 TargetFeatures = std::move(Value);
1038 else if (Name == "target_cpu")
1039 TargetCPU = std::move(Value);
1040 else
1041 return false;
1042 return true;
1043}
1044
1045SmallVector<std::pair<StringRef, StringRef>>
1046Module::GlobalAsmProperties::getAsStrings() const {
1047 SmallVector<std::pair<StringRef, StringRef>> Props;
1048 if (!TargetFeatures.empty())
1049 Props.emplace_back(Args: "target_features", Args: TargetFeatures);
1050 if (!TargetCPU.empty())
1051 Props.emplace_back(Args: "target_cpu", Args: TargetCPU);
1052 return Props;
1053}
1054