[ORC] Add std::tuple support to SimplePackedSerialization.
[llvm-project.git] / llvm / lib / IR / Module.cpp
blob63ea41fba89ab8efd3c9ae26f05135af36ffafb2
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.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/Module.h"
14 #include "SymbolTableListTraitsImpl.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/Attributes.h"
23 #include "llvm/IR/Comdat.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GVMaterializer.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalIFunc.h"
32 #include "llvm/IR/GlobalValue.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/ModuleSummaryIndex.h"
37 #include "llvm/IR/SymbolTableListTraits.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/TypeFinder.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/IR/ValueSymbolTable.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/CodeGen.h"
45 #include "llvm/Support/Error.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/RandomNumberGenerator.h"
49 #include "llvm/Support/VersionTuple.h"
50 #include <algorithm>
51 #include <cassert>
52 #include <cstdint>
53 #include <memory>
54 #include <utility>
55 #include <vector>
57 using namespace llvm;
59 //===----------------------------------------------------------------------===//
60 // Methods to implement the globals and functions lists.
63 // Explicit instantiations of SymbolTableListTraits since some of the methods
64 // are not in the public header file.
65 template class llvm::SymbolTableListTraits<Function>;
66 template class llvm::SymbolTableListTraits<GlobalVariable>;
67 template class llvm::SymbolTableListTraits<GlobalAlias>;
68 template class llvm::SymbolTableListTraits<GlobalIFunc>;
70 //===----------------------------------------------------------------------===//
71 // Primitive Module methods.
74 Module::Module(StringRef MID, LLVMContext &C)
75 : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>(-1)),
76 Materializer(), ModuleID(std::string(MID)),
77 SourceFileName(std::string(MID)), DL("") {
78 Context.addModule(this);
81 Module::~Module() {
82 Context.removeModule(this);
83 dropAllReferences();
84 GlobalList.clear();
85 FunctionList.clear();
86 AliasList.clear();
87 IFuncList.clear();
90 std::unique_ptr<RandomNumberGenerator>
91 Module::createRNG(const StringRef Name) const {
92 SmallString<32> Salt(Name);
94 // This RNG is guaranteed to produce the same random stream only
95 // when the Module ID and thus the input filename is the same. This
96 // might be problematic if the input filename extension changes
97 // (e.g. from .c to .bc or .ll).
99 // We could store this salt in NamedMetadata, but this would make
100 // the parameter non-const. This would unfortunately make this
101 // interface unusable by any Machine passes, since they only have a
102 // const reference to their IR Module. Alternatively we can always
103 // store salt metadata from the Module constructor.
104 Salt += sys::path::filename(getModuleIdentifier());
106 return std::unique_ptr<RandomNumberGenerator>(
107 new RandomNumberGenerator(Salt));
110 /// getNamedValue - Return the first global value in the module with
111 /// the specified name, of arbitrary type. This method returns null
112 /// if a global with the specified name is not found.
113 GlobalValue *Module::getNamedValue(StringRef Name) const {
114 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
117 unsigned Module::getNumNamedValues() const {
118 return getValueSymbolTable().size();
121 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
122 /// This ID is uniqued across modules in the current LLVMContext.
123 unsigned Module::getMDKindID(StringRef Name) const {
124 return Context.getMDKindID(Name);
127 /// getMDKindNames - Populate client supplied SmallVector with the name for
128 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
129 /// so it is filled in as an empty string.
130 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
131 return Context.getMDKindNames(Result);
134 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
135 return Context.getOperandBundleTags(Result);
138 //===----------------------------------------------------------------------===//
139 // Methods for easy access to the functions in the module.
142 // getOrInsertFunction - Look up the specified function in the module symbol
143 // table. If it does not exist, add a prototype for the function and return
144 // it. This is nice because it allows most passes to get away with not handling
145 // the symbol table directly for this common task.
147 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
148 AttributeList AttributeList) {
149 // See if we have a definition for the specified function already.
150 GlobalValue *F = getNamedValue(Name);
151 if (!F) {
152 // Nope, add it
153 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
154 DL.getProgramAddressSpace(), Name);
155 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
156 New->setAttributes(AttributeList);
157 FunctionList.push_back(New);
158 return {Ty, New}; // Return the new prototype.
161 // If the function exists but has the wrong type, return a bitcast to the
162 // right type.
163 auto *PTy = PointerType::get(Ty, F->getAddressSpace());
164 if (F->getType() != PTy)
165 return {Ty, ConstantExpr::getBitCast(F, PTy)};
167 // Otherwise, we just found the existing function or a prototype.
168 return {Ty, F};
171 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
172 return getOrInsertFunction(Name, Ty, AttributeList());
175 // getFunction - Look up the specified function in the module symbol table.
176 // If it does not exist, return null.
178 Function *Module::getFunction(StringRef Name) const {
179 return dyn_cast_or_null<Function>(getNamedValue(Name));
182 //===----------------------------------------------------------------------===//
183 // Methods for easy access to the global variables in the module.
186 /// getGlobalVariable - Look up the specified global variable in the module
187 /// symbol table. If it does not exist, return null. The type argument
188 /// should be the underlying type of the global, i.e., it should not have
189 /// the top-level PointerType, which represents the address of the global.
190 /// If AllowLocal is set to true, this function will return types that
191 /// have an local. By default, these types are not returned.
193 GlobalVariable *Module::getGlobalVariable(StringRef Name,
194 bool AllowLocal) const {
195 if (GlobalVariable *Result =
196 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
197 if (AllowLocal || !Result->hasLocalLinkage())
198 return Result;
199 return nullptr;
202 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
203 /// 1. If it does not exist, add a declaration of the global and return it.
204 /// 2. Else, the global exists but has the wrong type: return the function
205 /// with a constantexpr cast to the right type.
206 /// 3. Finally, if the existing global is the correct declaration, return the
207 /// existing global.
208 Constant *Module::getOrInsertGlobal(
209 StringRef Name, Type *Ty,
210 function_ref<GlobalVariable *()> CreateGlobalCallback) {
211 // See if we have a definition for the specified global already.
212 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
213 if (!GV)
214 GV = CreateGlobalCallback();
215 assert(GV && "The CreateGlobalCallback is expected to create a global");
217 // If the variable exists but has the wrong type, return a bitcast to the
218 // right type.
219 Type *GVTy = GV->getType();
220 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
221 if (GVTy != PTy)
222 return ConstantExpr::getBitCast(GV, PTy);
224 // Otherwise, we just found the existing function or a prototype.
225 return GV;
228 // Overload to construct a global variable using its constructor's defaults.
229 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
230 return getOrInsertGlobal(Name, Ty, [&] {
231 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
232 nullptr, Name);
236 //===----------------------------------------------------------------------===//
237 // Methods for easy access to the global variables in the module.
240 // getNamedAlias - Look up the specified global in the module symbol table.
241 // If it does not exist, return null.
243 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
244 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
247 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
248 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
251 /// getNamedMetadata - Return the first NamedMDNode in the module with the
252 /// specified name. This method returns null if a NamedMDNode with the
253 /// specified name is not found.
254 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
255 SmallString<256> NameData;
256 StringRef NameRef = Name.toStringRef(NameData);
257 return NamedMDSymTab.lookup(NameRef);
260 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
261 /// with the specified name. This method returns a new NamedMDNode if a
262 /// NamedMDNode with the specified name is not found.
263 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
264 NamedMDNode *&NMD = NamedMDSymTab[Name];
265 if (!NMD) {
266 NMD = new NamedMDNode(Name);
267 NMD->setParent(this);
268 NamedMDList.push_back(NMD);
270 return NMD;
273 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
274 /// delete it.
275 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
276 NamedMDSymTab.erase(NMD->getName());
277 NamedMDList.erase(NMD->getIterator());
280 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
281 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
282 uint64_t Val = Behavior->getLimitedValue();
283 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
284 MFB = static_cast<ModFlagBehavior>(Val);
285 return true;
288 return false;
291 bool Module::isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB,
292 MDString *&Key, Metadata *&Val) {
293 if (ModFlag.getNumOperands() < 3)
294 return false;
295 if (!isValidModFlagBehavior(ModFlag.getOperand(0), MFB))
296 return false;
297 MDString *K = dyn_cast_or_null<MDString>(ModFlag.getOperand(1));
298 if (!K)
299 return false;
300 Key = K;
301 Val = ModFlag.getOperand(2);
302 return true;
305 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
306 void Module::
307 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
308 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
309 if (!ModFlags) return;
311 for (const MDNode *Flag : ModFlags->operands()) {
312 ModFlagBehavior MFB;
313 MDString *Key = nullptr;
314 Metadata *Val = nullptr;
315 if (isValidModuleFlag(*Flag, MFB, Key, Val)) {
316 // Check the operands of the MDNode before accessing the operands.
317 // The verifier will actually catch these failures.
318 Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
323 /// Return the corresponding value if Key appears in module flags, otherwise
324 /// return null.
325 Metadata *Module::getModuleFlag(StringRef Key) const {
326 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
327 getModuleFlagsMetadata(ModuleFlags);
328 for (const ModuleFlagEntry &MFE : ModuleFlags) {
329 if (Key == MFE.Key->getString())
330 return MFE.Val;
332 return nullptr;
335 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
336 /// represents module-level flags. This method returns null if there are no
337 /// module-level flags.
338 NamedMDNode *Module::getModuleFlagsMetadata() const {
339 return getNamedMetadata("llvm.module.flags");
342 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
343 /// represents module-level flags. If module-level flags aren't found, it
344 /// creates the named metadata that contains them.
345 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
346 return getOrInsertNamedMetadata("llvm.module.flags");
349 /// addModuleFlag - Add a module-level flag to the module-level flags
350 /// metadata. It will create the module-level flags named metadata if it doesn't
351 /// already exist.
352 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
353 Metadata *Val) {
354 Type *Int32Ty = Type::getInt32Ty(Context);
355 Metadata *Ops[3] = {
356 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
357 MDString::get(Context, Key), Val};
358 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
360 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
361 Constant *Val) {
362 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
364 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
365 uint32_t Val) {
366 Type *Int32Ty = Type::getInt32Ty(Context);
367 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
369 void Module::addModuleFlag(MDNode *Node) {
370 assert(Node->getNumOperands() == 3 &&
371 "Invalid number of operands for module flag!");
372 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
373 isa<MDString>(Node->getOperand(1)) &&
374 "Invalid operand types for module flag!");
375 getOrInsertModuleFlagsMetadata()->addOperand(Node);
378 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
379 Metadata *Val) {
380 NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
381 // Replace the flag if it already exists.
382 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
383 MDNode *Flag = ModFlags->getOperand(I);
384 ModFlagBehavior MFB;
385 MDString *K = nullptr;
386 Metadata *V = nullptr;
387 if (isValidModuleFlag(*Flag, MFB, K, V) && K->getString() == Key) {
388 Flag->replaceOperandWith(2, Val);
389 return;
392 addModuleFlag(Behavior, Key, Val);
395 void Module::setDataLayout(StringRef Desc) {
396 DL.reset(Desc);
399 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
401 const DataLayout &Module::getDataLayout() const { return DL; }
403 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
404 return cast<DICompileUnit>(CUs->getOperand(Idx));
406 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
407 return cast<DICompileUnit>(CUs->getOperand(Idx));
410 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
411 while (CUs && (Idx < CUs->getNumOperands()) &&
412 ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
413 ++Idx;
416 iterator_range<Module::global_object_iterator> Module::global_objects() {
417 return concat<GlobalObject>(functions(), globals());
419 iterator_range<Module::const_global_object_iterator>
420 Module::global_objects() const {
421 return concat<const GlobalObject>(functions(), globals());
424 iterator_range<Module::global_value_iterator> Module::global_values() {
425 return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
427 iterator_range<Module::const_global_value_iterator>
428 Module::global_values() const {
429 return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
432 //===----------------------------------------------------------------------===//
433 // Methods to control the materialization of GlobalValues in the Module.
435 void Module::setMaterializer(GVMaterializer *GVM) {
436 assert(!Materializer &&
437 "Module already has a GVMaterializer. Call materializeAll"
438 " to clear it out before setting another one.");
439 Materializer.reset(GVM);
442 Error Module::materialize(GlobalValue *GV) {
443 if (!Materializer)
444 return Error::success();
446 return Materializer->materialize(GV);
449 Error Module::materializeAll() {
450 if (!Materializer)
451 return Error::success();
452 std::unique_ptr<GVMaterializer> M = std::move(Materializer);
453 return M->materializeModule();
456 Error Module::materializeMetadata() {
457 if (!Materializer)
458 return Error::success();
459 return Materializer->materializeMetadata();
462 //===----------------------------------------------------------------------===//
463 // Other module related stuff.
466 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
467 // If we have a materializer, it is possible that some unread function
468 // uses a type that is currently not visible to a TypeFinder, so ask
469 // the materializer which types it created.
470 if (Materializer)
471 return Materializer->getIdentifiedStructTypes();
473 std::vector<StructType *> Ret;
474 TypeFinder SrcStructTypes;
475 SrcStructTypes.run(*this, true);
476 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
477 return Ret;
480 std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
481 const FunctionType *Proto) {
482 auto Encode = [&BaseName](unsigned Suffix) {
483 return (Twine(BaseName) + "." + Twine(Suffix)).str();
487 // fast path - the prototype is already known
488 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
489 if (!UinItInserted.second)
490 return Encode(UinItInserted.first->second);
493 // Not known yet. A new entry was created with index 0. Check if there already
494 // exists a matching declaration, or select a new entry.
496 // Start looking for names with the current known maximum count (or 0).
497 auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
498 unsigned Count = NiidItInserted.first->second;
500 // This might be slow if a whole population of intrinsics already existed, but
501 // we cache the values for later usage.
502 std::string NewName;
503 while (true) {
504 NewName = Encode(Count);
505 GlobalValue *F = getNamedValue(NewName);
506 if (!F) {
507 // Reserve this entry for the new proto
508 UniquedIntrinsicNames[{Id, Proto}] = Count;
509 break;
512 // A declaration with this name already exists. Remember it.
513 FunctionType *FT = dyn_cast<FunctionType>(F->getValueType());
514 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
515 if (FT == Proto) {
516 // It was a declaration for our prototype. This entry was allocated in the
517 // beginning. Update the count to match the existing declaration.
518 UinItInserted.first->second = Count;
519 break;
522 ++Count;
525 NiidItInserted.first->second = Count + 1;
527 return NewName;
530 // dropAllReferences() - This function causes all the subelements to "let go"
531 // of all references that they are maintaining. This allows one to 'delete' a
532 // whole module at a time, even though there may be circular references... first
533 // all references are dropped, and all use counts go to zero. Then everything
534 // is deleted for real. Note that no operations are valid on an object that
535 // has "dropped all references", except operator delete.
537 void Module::dropAllReferences() {
538 for (Function &F : *this)
539 F.dropAllReferences();
541 for (GlobalVariable &GV : globals())
542 GV.dropAllReferences();
544 for (GlobalAlias &GA : aliases())
545 GA.dropAllReferences();
547 for (GlobalIFunc &GIF : ifuncs())
548 GIF.dropAllReferences();
551 unsigned Module::getNumberRegisterParameters() const {
552 auto *Val =
553 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
554 if (!Val)
555 return 0;
556 return cast<ConstantInt>(Val->getValue())->getZExtValue();
559 unsigned Module::getDwarfVersion() const {
560 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
561 if (!Val)
562 return 0;
563 return cast<ConstantInt>(Val->getValue())->getZExtValue();
566 bool Module::isDwarf64() const {
567 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64"));
568 return Val && cast<ConstantInt>(Val->getValue())->isOne();
571 unsigned Module::getCodeViewFlag() const {
572 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
573 if (!Val)
574 return 0;
575 return cast<ConstantInt>(Val->getValue())->getZExtValue();
578 unsigned Module::getInstructionCount() const {
579 unsigned NumInstrs = 0;
580 for (const Function &F : FunctionList)
581 NumInstrs += F.getInstructionCount();
582 return NumInstrs;
585 Comdat *Module::getOrInsertComdat(StringRef Name) {
586 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
587 Entry.second.Name = &Entry;
588 return &Entry.second;
591 PICLevel::Level Module::getPICLevel() const {
592 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
594 if (!Val)
595 return PICLevel::NotPIC;
597 return static_cast<PICLevel::Level>(
598 cast<ConstantInt>(Val->getValue())->getZExtValue());
601 void Module::setPICLevel(PICLevel::Level PL) {
602 addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
605 PIELevel::Level Module::getPIELevel() const {
606 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
608 if (!Val)
609 return PIELevel::Default;
611 return static_cast<PIELevel::Level>(
612 cast<ConstantInt>(Val->getValue())->getZExtValue());
615 void Module::setPIELevel(PIELevel::Level PL) {
616 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
619 Optional<CodeModel::Model> Module::getCodeModel() const {
620 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
622 if (!Val)
623 return None;
625 return static_cast<CodeModel::Model>(
626 cast<ConstantInt>(Val->getValue())->getZExtValue());
629 void Module::setCodeModel(CodeModel::Model CL) {
630 // Linking object files with different code models is undefined behavior
631 // because the compiler would have to generate additional code (to span
632 // longer jumps) if a larger code model is used with a smaller one.
633 // Therefore we will treat attempts to mix code models as an error.
634 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
637 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
638 if (Kind == ProfileSummary::PSK_CSInstr)
639 setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
640 else
641 setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
644 Metadata *Module::getProfileSummary(bool IsCS) const {
645 return (IsCS ? getModuleFlag("CSProfileSummary")
646 : getModuleFlag("ProfileSummary"));
649 bool Module::getSemanticInterposition() const {
650 Metadata *MF = getModuleFlag("SemanticInterposition");
652 auto *Val = cast_or_null<ConstantAsMetadata>(MF);
653 if (!Val)
654 return false;
656 return cast<ConstantInt>(Val->getValue())->getZExtValue();
659 void Module::setSemanticInterposition(bool SI) {
660 addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI);
663 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
664 OwnedMemoryBuffer = std::move(MB);
667 bool Module::getRtLibUseGOT() const {
668 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
669 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
672 void Module::setRtLibUseGOT() {
673 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
676 bool Module::getUwtable() const {
677 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable"));
678 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
681 void Module::setUwtable() { addModuleFlag(ModFlagBehavior::Max, "uwtable", 1); }
683 FramePointerKind Module::getFramePointer() const {
684 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer"));
685 return static_cast<FramePointerKind>(
686 Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
689 void Module::setFramePointer(FramePointerKind Kind) {
690 addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind));
693 StringRef Module::getStackProtectorGuard() const {
694 Metadata *MD = getModuleFlag("stack-protector-guard");
695 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
696 return MDS->getString();
697 return {};
700 void Module::setStackProtectorGuard(StringRef Kind) {
701 MDString *ID = MDString::get(getContext(), Kind);
702 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID);
705 StringRef Module::getStackProtectorGuardReg() const {
706 Metadata *MD = getModuleFlag("stack-protector-guard-reg");
707 if (auto *MDS = dyn_cast_or_null<MDString>(MD))
708 return MDS->getString();
709 return {};
712 void Module::setStackProtectorGuardReg(StringRef Reg) {
713 MDString *ID = MDString::get(getContext(), Reg);
714 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID);
717 int Module::getStackProtectorGuardOffset() const {
718 Metadata *MD = getModuleFlag("stack-protector-guard-offset");
719 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
720 return CI->getSExtValue();
721 return INT_MAX;
724 void Module::setStackProtectorGuardOffset(int Offset) {
725 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset);
728 unsigned Module::getOverrideStackAlignment() const {
729 Metadata *MD = getModuleFlag("override-stack-alignment");
730 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
731 return CI->getZExtValue();
732 return 0;
735 void Module::setOverrideStackAlignment(unsigned Align) {
736 addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align);
739 void Module::setSDKVersion(const VersionTuple &V) {
740 SmallVector<unsigned, 3> Entries;
741 Entries.push_back(V.getMajor());
742 if (auto Minor = V.getMinor()) {
743 Entries.push_back(*Minor);
744 if (auto Subminor = V.getSubminor())
745 Entries.push_back(*Subminor);
746 // Ignore the 'build' component as it can't be represented in the object
747 // file.
749 addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
750 ConstantDataArray::get(Context, Entries));
753 VersionTuple Module::getSDKVersion() const {
754 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
755 if (!CM)
756 return {};
757 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
758 if (!Arr)
759 return {};
760 auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
761 if (Index >= Arr->getNumElements())
762 return None;
763 return (unsigned)Arr->getElementAsInteger(Index);
765 auto Major = getVersionComponent(0);
766 if (!Major)
767 return {};
768 VersionTuple Result = VersionTuple(*Major);
769 if (auto Minor = getVersionComponent(1)) {
770 Result = VersionTuple(*Major, *Minor);
771 if (auto Subminor = getVersionComponent(2)) {
772 Result = VersionTuple(*Major, *Minor, *Subminor);
775 return Result;
778 GlobalVariable *llvm::collectUsedGlobalVariables(
779 const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
780 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
781 GlobalVariable *GV = M.getGlobalVariable(Name);
782 if (!GV || !GV->hasInitializer())
783 return GV;
785 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
786 for (Value *Op : Init->operands()) {
787 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
788 Vec.push_back(G);
790 return GV;
793 void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) {
794 if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
795 std::unique_ptr<ProfileSummary> ProfileSummary(
796 ProfileSummary::getFromMD(SummaryMD));
797 if (ProfileSummary) {
798 if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample ||
799 !ProfileSummary->isPartialProfile())
800 return;
801 uint64_t BlockCount = Index.getBlockCount();
802 uint32_t NumCounts = ProfileSummary->getNumCounts();
803 if (!NumCounts)
804 return;
805 double Ratio = (double)BlockCount / NumCounts;
806 ProfileSummary->setPartialProfileRatio(Ratio);
807 setProfileSummary(ProfileSummary->getMD(getContext()),
808 ProfileSummary::PSK_Sample);