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