LLVM 18.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"
42#include "llvm/Support/Error.h"
44#include "llvm/Support/Path.h"
47#include <algorithm>
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
73 : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>(-1)),
74 ModuleID(std::string(MID)), SourceFileName(std::string(MID)), DL(""),
75 IsNewDbgInfoFormat(false) {
76 Context.addModule(this);
77}
78
80 Context.removeModule(this);
82 GlobalList.clear();
83 FunctionList.clear();
84 AliasList.clear();
85 IFuncList.clear();
86}
87
88std::unique_ptr<RandomNumberGenerator>
91
92 // This RNG is guaranteed to produce the same random stream only
93 // when the Module ID and thus the input filename is the same. This
94 // might be problematic if the input filename extension changes
95 // (e.g. from .c to .bc or .ll).
96 //
97 // We could store this salt in NamedMetadata, but this would make
98 // the parameter non-const. This would unfortunately make this
99 // interface unusable by any Machine passes, since they only have a
100 // const reference to their IR Module. Alternatively we can always
101 // store salt metadata from the Module constructor.
103
104 return std::unique_ptr<RandomNumberGenerator>(
105 new RandomNumberGenerator(Salt));
106}
107
108/// getNamedValue - Return the first global value in the module with
109/// the specified name, of arbitrary type. This method returns null
110/// if a global with the specified name is not found.
112 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
113}
114
116 return getValueSymbolTable().size();
117}
118
119/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
120/// This ID is uniqued across modules in the current LLVMContext.
122 return Context.getMDKindID(Name);
123}
124
125/// getMDKindNames - Populate client supplied SmallVector with the name for
126/// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
127/// so it is filled in as an empty string.
129 return Context.getMDKindNames(Result);
130}
131
133 return Context.getOperandBundleTags(Result);
134}
135
136//===----------------------------------------------------------------------===//
137// Methods for easy access to the functions in the module.
138//
139
140// getOrInsertFunction - Look up the specified function in the module symbol
141// table. If it does not exist, add a prototype for the function and return
142// it. This is nice because it allows most passes to get away with not handling
143// the symbol table directly for this common task.
144//
147 // See if we have a definition for the specified function already.
149 if (!F) {
150 // Nope, add it
153 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
154 New->setAttributes(AttributeList);
155 FunctionList.push_back(New);
156 return {Ty, New}; // Return the new prototype.
157 }
158
159 // Otherwise, we just found the existing function or a prototype.
160 return {Ty, F};
161}
162
165}
166
167// getFunction - Look up the specified function in the module symbol table.
168// If it does not exist, return null.
169//
171 return dyn_cast_or_null<Function>(getNamedValue(Name));
172}
173
174//===----------------------------------------------------------------------===//
175// Methods for easy access to the global variables in the module.
176//
177
178/// getGlobalVariable - Look up the specified global variable in the module
179/// symbol table. If it does not exist, return null. The type argument
180/// should be the underlying type of the global, i.e., it should not have
181/// the top-level PointerType, which represents the address of the global.
182/// If AllowLocal is set to true, this function will return types that
183/// have an local. By default, these types are not returned.
184///
186 bool AllowLocal) const {
187 if (GlobalVariable *Result =
188 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
189 if (AllowLocal || !Result->hasLocalLinkage())
190 return Result;
191 return nullptr;
192}
193
194/// getOrInsertGlobal - Look up the specified global in the module symbol table.
195/// 1. If it does not exist, add a declaration of the global and return it.
196/// 2. Else, the global exists but has the wrong type: return the function
197/// with a constantexpr cast to the right type.
198/// 3. Finally, if the existing global is the correct declaration, return the
199/// existing global.
201 StringRef Name, Type *Ty,
202 function_ref<GlobalVariable *()> CreateGlobalCallback) {
203 // See if we have a definition for the specified global already.
204 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
205 if (!GV)
206 GV = CreateGlobalCallback();
207 assert(GV && "The CreateGlobalCallback is expected to create a global");
208
209 // Otherwise, we just found the existing function or a prototype.
210 return GV;
211}
212
213// Overload to construct a global variable using its constructor's defaults.
215 return getOrInsertGlobal(Name, Ty, [&] {
216 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
217 nullptr, Name);
218 });
219}
220
221//===----------------------------------------------------------------------===//
222// Methods for easy access to the global variables in the module.
223//
224
225// getNamedAlias - Look up the specified global in the module symbol table.
226// If it does not exist, return null.
227//
229 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
230}
231
233 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
234}
235
236/// getNamedMetadata - Return the first NamedMDNode in the module with the
237/// specified name. This method returns null if a NamedMDNode with the
238/// specified name is not found.
240 SmallString<256> NameData;
241 StringRef NameRef = Name.toStringRef(NameData);
242 return NamedMDSymTab.lookup(NameRef);
243}
244
245/// getOrInsertNamedMetadata - Return the first named MDNode in the module
246/// with the specified name. This method returns a new NamedMDNode if a
247/// NamedMDNode with the specified name is not found.
249 NamedMDNode *&NMD = NamedMDSymTab[Name];
250 if (!NMD) {
251 NMD = new NamedMDNode(Name);
252 NMD->setParent(this);
254 }
255 return NMD;
256}
257
258/// eraseNamedMetadata - Remove the given NamedMDNode from this module and
259/// delete it.
261 NamedMDSymTab.erase(NMD->getName());
262 eraseNamedMDNode(NMD);
263}
264
266 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
267 uint64_t Val = Behavior->getLimitedValue();
268 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
269 MFB = static_cast<ModFlagBehavior>(Val);
270 return true;
271 }
272 }
273 return false;
274}
275
277 MDString *&Key, Metadata *&Val) {
278 if (ModFlag.getNumOperands() < 3)
279 return false;
280 if (!isValidModFlagBehavior(ModFlag.getOperand(0), MFB))
281 return false;
282 MDString *K = dyn_cast_or_null<MDString>(ModFlag.getOperand(1));
283 if (!K)
284 return false;
285 Key = K;
286 Val = ModFlag.getOperand(2);
287 return true;
288}
289
290/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
293 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
294 if (!ModFlags) return;
295
296 for (const MDNode *Flag : ModFlags->operands()) {
297 ModFlagBehavior MFB;
298 MDString *Key = nullptr;
299 Metadata *Val = nullptr;
300 if (isValidModuleFlag(*Flag, MFB, Key, Val)) {
301 // Check the operands of the MDNode before accessing the operands.
302 // The verifier will actually catch these failures.
303 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
304 }
305 }
306}
307
308/// Return the corresponding value if Key appears in module flags, otherwise
309/// return null.
312 getModuleFlagsMetadata(ModuleFlags);
313 for (const ModuleFlagEntry &MFE : ModuleFlags) {
314 if (Key == MFE.Key->getString())
315 return MFE.Val;
316 }
317 return nullptr;
318}
319
320/// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
321/// represents module-level flags. This method returns null if there are no
322/// module-level flags.
324 return getNamedMetadata("llvm.module.flags");
325}
326
327/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
328/// represents module-level flags. If module-level flags aren't found, it
329/// creates the named metadata that contains them.
331 return getOrInsertNamedMetadata("llvm.module.flags");
332}
333
334/// addModuleFlag - Add a module-level flag to the module-level flags
335/// metadata. It will create the module-level flags named metadata if it doesn't
336/// already exist.
338 Metadata *Val) {
339 Type *Int32Ty = Type::getInt32Ty(Context);
340 Metadata *Ops[3] = {
342 MDString::get(Context, Key), Val};
344}
346 Constant *Val) {
347 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
348}
350 uint32_t Val) {
351 Type *Int32Ty = Type::getInt32Ty(Context);
352 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
353}
355 assert(Node->getNumOperands() == 3 &&
356 "Invalid number of operands for module flag!");
357 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
358 isa<MDString>(Node->getOperand(1)) &&
359 "Invalid operand types for module flag!");
361}
362
364 Metadata *Val) {
366 // Replace the flag if it already exists.
367 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
368 MDNode *Flag = ModFlags->getOperand(I);
369 ModFlagBehavior MFB;
370 MDString *K = nullptr;
371 Metadata *V = nullptr;
372 if (isValidModuleFlag(*Flag, MFB, K, V) && K->getString() == Key) {
373 Flag->replaceOperandWith(2, Val);
374 return;
375 }
376 }
377 addModuleFlag(Behavior, Key, Val);
378}
379
381 DL.reset(Desc);
382}
383
385
387 return cast<DICompileUnit>(CUs->getOperand(Idx));
388}
390 return cast<DICompileUnit>(CUs->getOperand(Idx));
391}
392
393void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
394 while (CUs && (Idx < CUs->getNumOperands()) &&
395 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
396 ++Idx;
397}
398
400 return concat<GlobalObject>(functions(), globals());
401}
404 return concat<const GlobalObject>(functions(), globals());
405}
406
408 return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
409}
412 return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
413}
414
415//===----------------------------------------------------------------------===//
416// Methods to control the materialization of GlobalValues in the Module.
417//
419 assert(!Materializer &&
420 "Module already has a GVMaterializer. Call materializeAll"
421 " to clear it out before setting another one.");
422 Materializer.reset(GVM);
423}
424
426 if (!Materializer)
427 return Error::success();
428
429 return Materializer->materialize(GV);
430}
431
433 if (!Materializer)
434 return Error::success();
435 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
436 return M->materializeModule();
437}
438
440 if (!Materializer)
441 return Error::success();
442 return Materializer->materializeMetadata();
443}
444
445//===----------------------------------------------------------------------===//
446// Other module related stuff.
447//
448
449std::vector<StructType *> Module::getIdentifiedStructTypes() const {
450 // If we have a materializer, it is possible that some unread function
451 // uses a type that is currently not visible to a TypeFinder, so ask
452 // the materializer which types it created.
453 if (Materializer)
454 return Materializer->getIdentifiedStructTypes();
455
456 std::vector<StructType *> Ret;
457 TypeFinder SrcStructTypes;
458 SrcStructTypes.run(*this, true);
459 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
460 return Ret;
461}
462
464 const FunctionType *Proto) {
465 auto Encode = [&BaseName](unsigned Suffix) {
466 return (Twine(BaseName) + "." + Twine(Suffix)).str();
467 };
468
469 {
470 // fast path - the prototype is already known
471 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
472 if (!UinItInserted.second)
473 return Encode(UinItInserted.first->second);
474 }
475
476 // Not known yet. A new entry was created with index 0. Check if there already
477 // exists a matching declaration, or select a new entry.
478
479 // Start looking for names with the current known maximum count (or 0).
480 auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
481 unsigned Count = NiidItInserted.first->second;
482
483 // This might be slow if a whole population of intrinsics already existed, but
484 // we cache the values for later usage.
485 std::string NewName;
486 while (true) {
487 NewName = Encode(Count);
488 GlobalValue *F = getNamedValue(NewName);
489 if (!F) {
490 // Reserve this entry for the new proto
491 UniquedIntrinsicNames[{Id, Proto}] = Count;
492 break;
493 }
494
495 // A declaration with this name already exists. Remember it.
496 FunctionType *FT = dyn_cast<FunctionType>(F->getValueType());
497 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
498 if (FT == Proto) {
499 // It was a declaration for our prototype. This entry was allocated in the
500 // beginning. Update the count to match the existing declaration.
501 UinItInserted.first->second = Count;
502 break;
503 }
504
505 ++Count;
506 }
507
508 NiidItInserted.first->second = Count + 1;
509
510 return NewName;
511}
512
513// dropAllReferences() - This function causes all the subelements to "let go"
514// of all references that they are maintaining. This allows one to 'delete' a
515// whole module at a time, even though there may be circular references... first
516// all references are dropped, and all use counts go to zero. Then everything
517// is deleted for real. Note that no operations are valid on an object that
518// has "dropped all references", except operator delete.
519//
521 for (Function &F : *this)
522 F.dropAllReferences();
523
524 for (GlobalVariable &GV : globals())
525 GV.dropAllReferences();
526
527 for (GlobalAlias &GA : aliases())
528 GA.dropAllReferences();
529
530 for (GlobalIFunc &GIF : ifuncs())
531 GIF.dropAllReferences();
532}
533
535 auto *Val =
536 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
537 if (!Val)
538 return 0;
539 return cast<ConstantInt>(Val->getValue())->getZExtValue();
540}
541
542unsigned Module::getDwarfVersion() const {
543 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
544 if (!Val)
545 return 0;
546 return cast<ConstantInt>(Val->getValue())->getZExtValue();
547}
548
549bool Module::isDwarf64() const {
550 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64"));
551 return Val && cast<ConstantInt>(Val->getValue())->isOne();
552}
553
554unsigned Module::getCodeViewFlag() const {
555 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
556 if (!Val)
557 return 0;
558 return cast<ConstantInt>(Val->getValue())->getZExtValue();
559}
560
562 unsigned NumInstrs = 0;
563 for (const Function &F : FunctionList)
564 NumInstrs += F.getInstructionCount();
565 return NumInstrs;
566}
567
569 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
570 Entry.second.Name = &Entry;
571 return &Entry.second;
572}
573
575 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
576
577 if (!Val)
578 return PICLevel::NotPIC;
579
580 return static_cast<PICLevel::Level>(
581 cast<ConstantInt>(Val->getValue())->getZExtValue());
582}
583
585 // The merge result of a non-PIC object and a PIC object can only be reliably
586 // used as a non-PIC object, so use the Min merge behavior.
587 addModuleFlag(ModFlagBehavior::Min, "PIC Level", PL);
588}
589
591 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
592
593 if (!Val)
594 return PIELevel::Default;
595
596 return static_cast<PIELevel::Level>(
597 cast<ConstantInt>(Val->getValue())->getZExtValue());
598}
599
601 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
602}
603
604std::optional<CodeModel::Model> Module::getCodeModel() const {
605 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
606
607 if (!Val)
608 return std::nullopt;
609
610 return static_cast<CodeModel::Model>(
611 cast<ConstantInt>(Val->getValue())->getZExtValue());
612}
613
615 // Linking object files with different code models is undefined behavior
616 // because the compiler would have to generate additional code (to span
617 // longer jumps) if a larger code model is used with a smaller one.
618 // Therefore we will treat attempts to mix code models as an error.
619 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
620}
621
622std::optional<uint64_t> Module::getLargeDataThreshold() const {
623 auto *Val =
624 cast_or_null<ConstantAsMetadata>(getModuleFlag("Large Data Threshold"));
625
626 if (!Val)
627 return std::nullopt;
628
629 return cast<ConstantInt>(Val->getValue())->getZExtValue();
630}
631
633 // Since the large data threshold goes along with the code model, the merge
634 // behavior is the same.
635 addModuleFlag(ModFlagBehavior::Error, "Large Data Threshold",
636 ConstantInt::get(Type::getInt64Ty(Context), Threshold));
637}
638
640 if (Kind == ProfileSummary::PSK_CSInstr)
641 setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
642 else
643 setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
644}
645
647 return (IsCS ? getModuleFlag("CSProfileSummary")
648 : getModuleFlag("ProfileSummary"));
649}
650
652 Metadata *MF = getModuleFlag("SemanticInterposition");
653
654 auto *Val = cast_or_null<ConstantAsMetadata>(MF);
655 if (!Val)
656 return false;
657
658 return cast<ConstantInt>(Val->getValue())->getZExtValue();
659}
660
662 addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI);
663}
664
665void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
666 OwnedMemoryBuffer = std::move(MB);
667}
668
670 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
671 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
672}
673
675 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
676}
677
679 auto *Val = cast_or_null<ConstantAsMetadata>(
680 getModuleFlag("direct-access-external-data"));
681 if (Val)
682 return cast<ConstantInt>(Val->getValue())->getZExtValue() > 0;
683 return getPICLevel() == PICLevel::NotPIC;
684}
685
687 addModuleFlag(ModFlagBehavior::Max, "direct-access-external-data", Value);
688}
689
691 if (auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable")))
692 return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue());
693 return UWTableKind::None;
694}
695
698}
699
701 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer"));
702 return static_cast<FramePointerKind>(
703 Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
704}
705
707 addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind));
708}
709
711 Metadata *MD = getModuleFlag("stack-protector-guard");
712 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
713 return MDS->getString();
714 return {};
715}
716
719 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID);
720}
721
723 Metadata *MD = getModuleFlag("stack-protector-guard-reg");
724 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
725 return MDS->getString();
726 return {};
727}
728
731 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID);
732}
733
735 Metadata *MD = getModuleFlag("stack-protector-guard-symbol");
736 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
737 return MDS->getString();
738 return {};
739}
740
742 MDString *ID = MDString::get(getContext(), Symbol);
743 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-symbol", ID);
744}
745
747 Metadata *MD = getModuleFlag("stack-protector-guard-offset");
748 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
749 return CI->getSExtValue();
750 return INT_MAX;
751}
752
754 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset);
755}
756
758 Metadata *MD = getModuleFlag("override-stack-alignment");
759 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
760 return CI->getZExtValue();
761 return 0;
762}
763
765 Metadata *MD = getModuleFlag("MaxTLSAlign");
766 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
767 return CI->getZExtValue();
768 return 0;
769}
770
772 addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align);
773}
774
777 Entries.push_back(V.getMajor());
778 if (auto Minor = V.getMinor()) {
779 Entries.push_back(*Minor);
780 if (auto Subminor = V.getSubminor())
781 Entries.push_back(*Subminor);
782 // Ignore the 'build' component as it can't be represented in the object
783 // file.
784 }
785 M.addModuleFlag(Module::ModFlagBehavior::Warning, Name,
786 ConstantDataArray::get(M.getContext(), Entries));
787}
788
790 addSDKVersionMD(V, *this, "SDK Version");
791}
792
794 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD);
795 if (!CM)
796 return {};
797 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
798 if (!Arr)
799 return {};
800 auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> {
801 if (Index >= Arr->getNumElements())
802 return std::nullopt;
803 return (unsigned)Arr->getElementAsInteger(Index);
804 };
805 auto Major = getVersionComponent(0);
806 if (!Major)
807 return {};
808 VersionTuple Result = VersionTuple(*Major);
809 if (auto Minor = getVersionComponent(1)) {
810 Result = VersionTuple(*Major, *Minor);
811 if (auto Subminor = getVersionComponent(2)) {
812 Result = VersionTuple(*Major, *Minor, *Subminor);
813 }
814 }
815 return Result;
816}
817
819 return getSDKVersionMD(getModuleFlag("SDK Version"));
820}
821
823 const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
824 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
825 GlobalVariable *GV = M.getGlobalVariable(Name);
826 if (!GV || !GV->hasInitializer())
827 return GV;
828
829 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
830 for (Value *Op : Init->operands()) {
831 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
832 Vec.push_back(G);
833 }
834 return GV;
835}
836
838 if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
839 std::unique_ptr<ProfileSummary> ProfileSummary(
840 ProfileSummary::getFromMD(SummaryMD));
841 if (ProfileSummary) {
844 return;
845 uint64_t BlockCount = Index.getBlockCount();
846 uint32_t NumCounts = ProfileSummary->getNumCounts();
847 if (!NumCounts)
848 return;
849 double Ratio = (double)BlockCount / NumCounts;
853 }
854 }
855}
856
858 if (const auto *MD = getModuleFlag("darwin.target_variant.triple"))
859 return cast<MDString>(MD)->getString();
860 return "";
861}
862
864 addModuleFlag(ModFlagBehavior::Override, "darwin.target_variant.triple",
866}
867
869 return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version"));
870}
871
873 addSDKVersionMD(Version, *this, "darwin.target_variant.SDK Version");
874}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the StringMap class.
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
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:109
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
This file contains the declarations for metadata subclasses.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
static VersionTuple getSDKVersionMD(Metadata *MD)
Definition: Module.cpp:793
static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name)
Definition: Module.cpp:775
Module.h This file contains the declarations for the Module class.
IntegerType * Int32Ty
LLVMContext & Context
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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:408
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:506
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition: Constants.h:690
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
This is an important base class in LLVM.
Definition: Constant.h:41
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:110
unsigned getProgramAddressSpace() const
Definition: DataLayout.h:293
void reset(StringRef LayoutDescription)
Parse a data layout string (with fallback to default values).
Definition: DataLayout.cpp:195
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
Class to represent function types.
Definition: DerivedTypes.h:103
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:162
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:48
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:67
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
void getOperandBundleTags(SmallVectorImpl< StringRef > &Result) const
getOperandBundleTags - Populate client supplied SmallVector with the bundle tags registered in this L...
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
getMDKindNames - Populate client supplied SmallVector with the name for custom metadata IDs registere...
Metadata node.
Definition: Metadata.h:1037
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1391
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1504
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1397
A single uniqued string.
Definition: Metadata.h:698
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:559
Root of the metadata hierarchy.
Definition: Metadata.h:62
Class to hold module path string table and global value map, and encapsulate methods for operating on...
DICompileUnit * operator*() const
Definition: Module.cpp:386
DICompileUnit * operator->() const
Definition: Module.cpp:389
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static bool isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB, MDString *&Key, Metadata *&Val)
Check if the given module flag metadata represents a valid module flag, and store the flag behavior,...
Definition: Module.cpp:276
void setStackProtectorGuardSymbol(StringRef Symbol)
Definition: Module.cpp:741
void setSemanticInterposition(bool)
Set whether semantic interposition is to be respected.
Definition: Module.cpp:661
void eraseNamedMDNode(NamedMDNode *MDNode)
Remove MDNode from the list and delete it.
Definition: Module.h:628
ModFlagBehavior
This enumeration defines the supported behaviors of module flags.
Definition: Module.h:115
@ Override
Uses the specified value, regardless of the behavior or value of the other module.
Definition: Module.h:136
@ Warning
Emits a warning if two values disagree.
Definition: Module.h:122
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
Definition: Module.h:118
@ ModFlagBehaviorFirstVal
Definition: Module.h:153
@ Min
Takes the min of the two values, which are required to be integers.
Definition: Module.h:150
@ Max
Takes the max of the two values, which are required to be integers.
Definition: Module.h:147
@ ModFlagBehaviorLastVal
Definition: Module.h:154
llvm::Error materializeAll()
Make sure all GlobalValues in this Module are fully read and clear the Materializer.
Definition: Module.cpp:432
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:283
void setOverrideStackAlignment(unsigned Align)
Definition: Module.cpp:771
void setDirectAccessExternalData(bool Value)
Definition: Module.cpp:686
unsigned getMaxTLSAlignment() const
Definition: Module.cpp:764
void setOwnedMemoryBuffer(std::unique_ptr< MemoryBuffer > MB)
Take ownership of the given memory buffer.
Definition: Module.cpp:665
void setMaterializer(GVMaterializer *GVM)
Sets the GVMaterializer to GVM.
Definition: Module.cpp:418
llvm::Error materialize(GlobalValue *GV)
Make sure the GlobalValue is fully read.
Definition: Module.cpp:425
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:170
void setCodeModel(CodeModel::Model CL)
Set the code model (tiny, small, kernel, medium or large)
Definition: Module.cpp:614
StringRef getStackProtectorGuardSymbol() const
Get/set a symbol to use as the stack protector guard.
Definition: Module.cpp:734
iterator_range< ifunc_iterator > ifuncs()
Definition: Module.h:746
bool getSemanticInterposition() const
Returns whether semantic interposition is to be respected.
Definition: Module.cpp:651
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
Populate client supplied SmallVector with the name for custom metadata IDs registered in this LLVMCon...
Definition: Module.cpp:128
Module(StringRef ModuleID, LLVMContext &C)
The Module constructor.
Definition: Module.cpp:72
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:239
void setRtLibUseGOT()
Set that PLT should be avoid for RTLib calls.
Definition: Module.cpp:674
llvm::Error materializeMetadata()
Definition: Module.cpp:439
NamedMDNode * getOrInsertModuleFlagsMetadata()
Returns the NamedMDNode in the module that represents module-level flags.
Definition: Module.cpp:330
iterator_range< iterator > functions()
Definition: Module.h:710
void eraseNamedMetadata(NamedMDNode *NMD)
Remove the given NamedMDNode from this module and delete it.
Definition: Module.cpp:260
unsigned getNumNamedValues() const
Return the number of global values in the module.
Definition: Module.cpp:115
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
Definition: Module.cpp:121
void setFramePointer(FramePointerKind Kind)
Definition: Module.cpp:706
std::optional< uint64_t > getLargeDataThreshold() const
Returns the code model (tiny, small, kernel, medium or large model)
Definition: Module.cpp:622
StringRef getStackProtectorGuard() const
Get/set what kind of stack protector guard to use.
Definition: Module.cpp:710
bool getRtLibUseGOT() const
Returns true if PLT should be avoided for RTLib calls.
Definition: Module.cpp:669
void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val)
Like addModuleFlag but replaces the old module flag if it already exists.
Definition: Module.cpp:363
UWTableKind getUwtable() const
Get/set whether synthesized functions should get the uwtable attribute.
Definition: Module.cpp:690
void dropAllReferences()
This function causes all the subinstructions to "let go" of all references that they are maintaining.
Definition: Module.cpp:520
void setStackProtectorGuard(StringRef Kind)
Definition: Module.cpp:717
iterator_range< alias_iterator > aliases()
Definition: Module.h:728
void setProfileSummary(Metadata *M, ProfileSummary::Kind Kind)
Attach profile summary metadata to this module.
Definition: Module.cpp:639
void setUwtable(UWTableKind Kind)
Definition: Module.cpp:696
unsigned getCodeViewFlag() const
Returns the CodeView Version by checking module flags.
Definition: Module.cpp:554
void setPartialSampleProfileRatio(const ModuleSummaryIndex &Index)
Set the partial sample profile ratio in the profile summary module flag, if applicable.
Definition: Module.cpp:837
std::string getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id, const FunctionType *Proto)
Return a unique name for an intrinsic whose mangling is based on an unnamed type.
Definition: Module.cpp:463
~Module()
The module destructor. This will dropAllReferences.
Definition: Module.cpp:79
FramePointerKind getFramePointer() const
Get/set whether synthesized functions should get the "frame-pointer" attribute.
Definition: Module.cpp:700
unsigned getOverrideStackAlignment() const
Get/set the stack alignment overridden from the default.
Definition: Module.cpp:757
void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val)
Add a module-level flag to the module-level flags metadata.
Definition: Module.cpp:337
void setStackProtectorGuardReg(StringRef Reg)
Definition: Module.cpp:729
PICLevel::Level getPICLevel() const
Returns the PIC level (small or large model)
Definition: Module.cpp:574
std::unique_ptr< RandomNumberGenerator > createRNG(const StringRef Name) const
Get a RandomNumberGenerator salted for use with this module.
Definition: Module.cpp:89
iterator_range< global_iterator > globals()
Definition: Module.h:688
std::vector< StructType * > getIdentifiedStructTypes() const
Definition: Module.cpp:449
void setDarwinTargetVariantTriple(StringRef T)
Set the target variant triple which is a string describing a variant of the target host platform.
Definition: Module.cpp:863
void setPICLevel(PICLevel::Level PL)
Set the PIC level (small or large model)
Definition: Module.cpp:584
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:249
unsigned getNumberRegisterParameters() const
Returns the Number of Register ParametersDwarf Version by checking module flags.
Definition: Module.cpp:534
void insertNamedMDNode(NamedMDNode *MDNode)
Insert MDNode at the end of the alias list and take ownership.
Definition: Module.h:630
GlobalIFunc * getNamedIFunc(StringRef Name) const
Return the global ifunc in the module with the specified name, of arbitrary type.
Definition: Module.cpp:232
StringRef getStackProtectorGuardReg() const
Get/set which register to use as the stack protector guard register.
Definition: Module.cpp:722
unsigned getDwarfVersion() const
Returns the Dwarf Version by checking module flags.
Definition: Module.cpp:542
void setDataLayout(StringRef Desc)
Set the data layout.
Definition: Module.cpp:380
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition: Module.h:435
void setLargeDataThreshold(uint64_t Threshold)
Set the code model (tiny, small, kernel, medium or large)
Definition: Module.cpp:632
bool isDwarf64() const
Returns the DWARF format by checking module flags.
Definition: Module.cpp:549
static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB)
Checks if Metadata represents a valid ModFlagBehavior, and stores the converted result in MFB.
Definition: Module.cpp:265
const ValueSymbolTable & getValueSymbolTable() const
Get the symbol table of global variable and function identifiers.
Definition: Module.h:668
void setStackProtectorGuardOffset(int Offset)
Definition: Module.cpp:753
iterator_range< global_object_iterator > global_objects()
Definition: Module.cpp:399
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition: Module.cpp:111
unsigned getInstructionCount() const
Returns the number of non-debug IR instructions in the module.
Definition: Module.cpp:561
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition: Module.cpp:248
void getOperandBundleTags(SmallVectorImpl< StringRef > &Result) const
Populate client supplied SmallVector with the bundle tags registered in this LLVMContext.
Definition: Module.cpp:132
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:568
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:145
Constant * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
Definition: Module.cpp:200
std::optional< CodeModel::Model > getCodeModel() const
Returns the code model (tiny, small, kernel, medium or large model)
Definition: Module.cpp:604
VersionTuple getDarwinTargetVariantSDKVersion() const
Get the target variant version build SDK version metadata.
Definition: Module.cpp:868
void setPIELevel(PIELevel::Level PL)
Set the PIE level (small or large model)
Definition: Module.cpp:600
VersionTuple getSDKVersion() const
Get the build SDK version metadata.
Definition: Module.cpp:818
NamedMDNode * getModuleFlagsMetadata() const
Returns the NamedMDNode in the module that represents module-level flags.
Definition: Module.cpp:323
GlobalAlias * getNamedAlias(StringRef Name) const
Return the global alias in the module with the specified name, of arbitrary type.
Definition: Module.cpp:228
void setDarwinTargetVariantSDKVersion(VersionTuple Version)
Set the target variant version build SDK version metadata.
Definition: Module.cpp:872
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition: Module.cpp:590
StringRef getDarwinTargetVariantTriple() const
Get the target variant triple which is a string describing a variant of the target host platform.
Definition: Module.cpp:857
void setSDKVersion(const VersionTuple &V)
Attach a build SDK version metadata to this module.
Definition: Module.cpp:789
iterator_range< global_value_iterator > global_values()
Definition: Module.cpp:407
int getStackProtectorGuardOffset() const
Get/set what offset from the stack protector to use.
Definition: Module.cpp:746
bool getDirectAccessExternalData() const
Get/set whether referencing global variables can use direct access relocations on ELF targets.
Definition: Module.cpp:678
Metadata * getProfileSummary(bool IsCS) const
Returns profile summary metadata.
Definition: Module.cpp:646
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition: Module.cpp:310
A tuple of MDNodes.
Definition: Metadata.h:1692
StringRef getName() const
Definition: Metadata.cpp:1358
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1341
unsigned getNumOperands() const
Definition: Metadata.cpp:1337
iterator_range< op_iterator > operands()
Definition: Metadata.h:1788
void addOperand(MDNode *M)
Definition: Metadata.cpp:1347
void setPartialProfileRatio(double R)
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
static ProfileSummary * getFromMD(Metadata *MD)
Construct profile summary from metdata.
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:577
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
ValueTy lookup(StringRef Key) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: StringMap.h:234
void erase(iterator I)
Definition: StringMap.h:382
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:287
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
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
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
This class provides a symbol table of name/value pairs.
unsigned size() const
The number of name/type pairs is returned.
LLVM Value Representation.
Definition: Value.h:74
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:29
An efficient, type-erasing, non-owning reference to a callable.
void push_back(pointer val)
Definition: ilist.h:250
void clear()
Definition: ilist.h:246
A range adaptor for a pair of iterators.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:579
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:440
FramePointerKind
Definition: CodeGen.h:90
UWTableKind
Definition: CodeGen.h:120
@ None
No unwind table requested.
@ Other
Any other memory.
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:822
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
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.