xref: /openbsd/gnu/llvm/llvm/lib/IR/Module.cpp (revision d415bd75)
109467b48Spatrick //===- Module.cpp - Implement the Module class ----------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the Module class for the IR library.
1009467b48Spatrick //
1109467b48Spatrick //===----------------------------------------------------------------------===//
1209467b48Spatrick 
1309467b48Spatrick #include "llvm/IR/Module.h"
1409467b48Spatrick #include "SymbolTableListTraitsImpl.h"
1509467b48Spatrick #include "llvm/ADT/SmallString.h"
1609467b48Spatrick #include "llvm/ADT/SmallVector.h"
1709467b48Spatrick #include "llvm/ADT/StringMap.h"
1809467b48Spatrick #include "llvm/ADT/StringRef.h"
1909467b48Spatrick #include "llvm/ADT/Twine.h"
2009467b48Spatrick #include "llvm/IR/Attributes.h"
2109467b48Spatrick #include "llvm/IR/Comdat.h"
2209467b48Spatrick #include "llvm/IR/Constants.h"
2309467b48Spatrick #include "llvm/IR/DataLayout.h"
2409467b48Spatrick #include "llvm/IR/DebugInfoMetadata.h"
2509467b48Spatrick #include "llvm/IR/DerivedTypes.h"
2609467b48Spatrick #include "llvm/IR/Function.h"
2709467b48Spatrick #include "llvm/IR/GVMaterializer.h"
2809467b48Spatrick #include "llvm/IR/GlobalAlias.h"
2909467b48Spatrick #include "llvm/IR/GlobalIFunc.h"
3009467b48Spatrick #include "llvm/IR/GlobalValue.h"
3109467b48Spatrick #include "llvm/IR/GlobalVariable.h"
3209467b48Spatrick #include "llvm/IR/LLVMContext.h"
3309467b48Spatrick #include "llvm/IR/Metadata.h"
34097a140dSpatrick #include "llvm/IR/ModuleSummaryIndex.h"
3509467b48Spatrick #include "llvm/IR/SymbolTableListTraits.h"
3609467b48Spatrick #include "llvm/IR/Type.h"
3709467b48Spatrick #include "llvm/IR/TypeFinder.h"
3809467b48Spatrick #include "llvm/IR/Value.h"
3909467b48Spatrick #include "llvm/IR/ValueSymbolTable.h"
4009467b48Spatrick #include "llvm/Support/Casting.h"
4109467b48Spatrick #include "llvm/Support/CodeGen.h"
4209467b48Spatrick #include "llvm/Support/Error.h"
4309467b48Spatrick #include "llvm/Support/MemoryBuffer.h"
4409467b48Spatrick #include "llvm/Support/Path.h"
4509467b48Spatrick #include "llvm/Support/RandomNumberGenerator.h"
4609467b48Spatrick #include "llvm/Support/VersionTuple.h"
4709467b48Spatrick #include <algorithm>
4809467b48Spatrick #include <cassert>
4909467b48Spatrick #include <cstdint>
5009467b48Spatrick #include <memory>
51*d415bd75Srobert #include <optional>
5209467b48Spatrick #include <utility>
5309467b48Spatrick #include <vector>
5409467b48Spatrick 
5509467b48Spatrick using namespace llvm;
5609467b48Spatrick 
5709467b48Spatrick //===----------------------------------------------------------------------===//
5809467b48Spatrick // Methods to implement the globals and functions lists.
5909467b48Spatrick //
6009467b48Spatrick 
6109467b48Spatrick // Explicit instantiations of SymbolTableListTraits since some of the methods
6209467b48Spatrick // are not in the public header file.
6309467b48Spatrick template class llvm::SymbolTableListTraits<Function>;
6409467b48Spatrick template class llvm::SymbolTableListTraits<GlobalVariable>;
6509467b48Spatrick template class llvm::SymbolTableListTraits<GlobalAlias>;
6609467b48Spatrick template class llvm::SymbolTableListTraits<GlobalIFunc>;
6709467b48Spatrick 
6809467b48Spatrick //===----------------------------------------------------------------------===//
6909467b48Spatrick // Primitive Module methods.
7009467b48Spatrick //
7109467b48Spatrick 
Module(StringRef MID,LLVMContext & C)7209467b48Spatrick Module::Module(StringRef MID, LLVMContext &C)
7373471bf0Spatrick     : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>(-1)),
74*d415bd75Srobert       ModuleID(std::string(MID)), SourceFileName(std::string(MID)), DL("") {
7509467b48Spatrick   Context.addModule(this);
7609467b48Spatrick }
7709467b48Spatrick 
~Module()7809467b48Spatrick Module::~Module() {
7909467b48Spatrick   Context.removeModule(this);
8009467b48Spatrick   dropAllReferences();
8109467b48Spatrick   GlobalList.clear();
8209467b48Spatrick   FunctionList.clear();
8309467b48Spatrick   AliasList.clear();
8409467b48Spatrick   IFuncList.clear();
8509467b48Spatrick }
8609467b48Spatrick 
87097a140dSpatrick std::unique_ptr<RandomNumberGenerator>
createRNG(const StringRef Name) const88097a140dSpatrick Module::createRNG(const StringRef Name) const {
89097a140dSpatrick   SmallString<32> Salt(Name);
9009467b48Spatrick 
9109467b48Spatrick   // This RNG is guaranteed to produce the same random stream only
9209467b48Spatrick   // when the Module ID and thus the input filename is the same. This
9309467b48Spatrick   // might be problematic if the input filename extension changes
9409467b48Spatrick   // (e.g. from .c to .bc or .ll).
9509467b48Spatrick   //
9609467b48Spatrick   // We could store this salt in NamedMetadata, but this would make
9709467b48Spatrick   // the parameter non-const. This would unfortunately make this
9809467b48Spatrick   // interface unusable by any Machine passes, since they only have a
9909467b48Spatrick   // const reference to their IR Module. Alternatively we can always
10009467b48Spatrick   // store salt metadata from the Module constructor.
10109467b48Spatrick   Salt += sys::path::filename(getModuleIdentifier());
10209467b48Spatrick 
103097a140dSpatrick   return std::unique_ptr<RandomNumberGenerator>(
104097a140dSpatrick       new RandomNumberGenerator(Salt));
10509467b48Spatrick }
10609467b48Spatrick 
10709467b48Spatrick /// getNamedValue - Return the first global value in the module with
10809467b48Spatrick /// the specified name, of arbitrary type.  This method returns null
10909467b48Spatrick /// if a global with the specified name is not found.
getNamedValue(StringRef Name) const11009467b48Spatrick GlobalValue *Module::getNamedValue(StringRef Name) const {
11109467b48Spatrick   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
11209467b48Spatrick }
11309467b48Spatrick 
getNumNamedValues() const11473471bf0Spatrick unsigned Module::getNumNamedValues() const {
11573471bf0Spatrick   return getValueSymbolTable().size();
11673471bf0Spatrick }
11773471bf0Spatrick 
11809467b48Spatrick /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
11909467b48Spatrick /// This ID is uniqued across modules in the current LLVMContext.
getMDKindID(StringRef Name) const12009467b48Spatrick unsigned Module::getMDKindID(StringRef Name) const {
12109467b48Spatrick   return Context.getMDKindID(Name);
12209467b48Spatrick }
12309467b48Spatrick 
12409467b48Spatrick /// getMDKindNames - Populate client supplied SmallVector with the name for
12509467b48Spatrick /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
12609467b48Spatrick /// so it is filled in as an empty string.
getMDKindNames(SmallVectorImpl<StringRef> & Result) const12709467b48Spatrick void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
12809467b48Spatrick   return Context.getMDKindNames(Result);
12909467b48Spatrick }
13009467b48Spatrick 
getOperandBundleTags(SmallVectorImpl<StringRef> & Result) const13109467b48Spatrick void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
13209467b48Spatrick   return Context.getOperandBundleTags(Result);
13309467b48Spatrick }
13409467b48Spatrick 
13509467b48Spatrick //===----------------------------------------------------------------------===//
13609467b48Spatrick // Methods for easy access to the functions in the module.
13709467b48Spatrick //
13809467b48Spatrick 
13909467b48Spatrick // getOrInsertFunction - Look up the specified function in the module symbol
14009467b48Spatrick // table.  If it does not exist, add a prototype for the function and return
14109467b48Spatrick // it.  This is nice because it allows most passes to get away with not handling
14209467b48Spatrick // the symbol table directly for this common task.
14309467b48Spatrick //
getOrInsertFunction(StringRef Name,FunctionType * Ty,AttributeList AttributeList)14409467b48Spatrick FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
14509467b48Spatrick                                            AttributeList AttributeList) {
14609467b48Spatrick   // See if we have a definition for the specified function already.
14709467b48Spatrick   GlobalValue *F = getNamedValue(Name);
14809467b48Spatrick   if (!F) {
14909467b48Spatrick     // Nope, add it
15009467b48Spatrick     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
15109467b48Spatrick                                      DL.getProgramAddressSpace(), Name);
15209467b48Spatrick     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
15309467b48Spatrick       New->setAttributes(AttributeList);
15409467b48Spatrick     FunctionList.push_back(New);
15509467b48Spatrick     return {Ty, New}; // Return the new prototype.
15609467b48Spatrick   }
15709467b48Spatrick 
15809467b48Spatrick   // If the function exists but has the wrong type, return a bitcast to the
15909467b48Spatrick   // right type.
16009467b48Spatrick   auto *PTy = PointerType::get(Ty, F->getAddressSpace());
16109467b48Spatrick   if (F->getType() != PTy)
16209467b48Spatrick     return {Ty, ConstantExpr::getBitCast(F, PTy)};
16309467b48Spatrick 
16409467b48Spatrick   // Otherwise, we just found the existing function or a prototype.
16509467b48Spatrick   return {Ty, F};
16609467b48Spatrick }
16709467b48Spatrick 
getOrInsertFunction(StringRef Name,FunctionType * Ty)16809467b48Spatrick FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
16909467b48Spatrick   return getOrInsertFunction(Name, Ty, AttributeList());
17009467b48Spatrick }
17109467b48Spatrick 
17209467b48Spatrick // getFunction - Look up the specified function in the module symbol table.
17309467b48Spatrick // If it does not exist, return null.
17409467b48Spatrick //
getFunction(StringRef Name) const17509467b48Spatrick Function *Module::getFunction(StringRef Name) const {
17609467b48Spatrick   return dyn_cast_or_null<Function>(getNamedValue(Name));
17709467b48Spatrick }
17809467b48Spatrick 
17909467b48Spatrick //===----------------------------------------------------------------------===//
18009467b48Spatrick // Methods for easy access to the global variables in the module.
18109467b48Spatrick //
18209467b48Spatrick 
18309467b48Spatrick /// getGlobalVariable - Look up the specified global variable in the module
18409467b48Spatrick /// symbol table.  If it does not exist, return null.  The type argument
18509467b48Spatrick /// should be the underlying type of the global, i.e., it should not have
18609467b48Spatrick /// the top-level PointerType, which represents the address of the global.
18709467b48Spatrick /// If AllowLocal is set to true, this function will return types that
18809467b48Spatrick /// have an local. By default, these types are not returned.
18909467b48Spatrick ///
getGlobalVariable(StringRef Name,bool AllowLocal) const19009467b48Spatrick GlobalVariable *Module::getGlobalVariable(StringRef Name,
19109467b48Spatrick                                           bool AllowLocal) const {
19209467b48Spatrick   if (GlobalVariable *Result =
19309467b48Spatrick       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
19409467b48Spatrick     if (AllowLocal || !Result->hasLocalLinkage())
19509467b48Spatrick       return Result;
19609467b48Spatrick   return nullptr;
19709467b48Spatrick }
19809467b48Spatrick 
19909467b48Spatrick /// getOrInsertGlobal - Look up the specified global in the module symbol table.
20009467b48Spatrick ///   1. If it does not exist, add a declaration of the global and return it.
20109467b48Spatrick ///   2. Else, the global exists but has the wrong type: return the function
20209467b48Spatrick ///      with a constantexpr cast to the right type.
20309467b48Spatrick ///   3. Finally, if the existing global is the correct declaration, return the
20409467b48Spatrick ///      existing global.
getOrInsertGlobal(StringRef Name,Type * Ty,function_ref<GlobalVariable * ()> CreateGlobalCallback)20509467b48Spatrick Constant *Module::getOrInsertGlobal(
20609467b48Spatrick     StringRef Name, Type *Ty,
20709467b48Spatrick     function_ref<GlobalVariable *()> CreateGlobalCallback) {
20809467b48Spatrick   // See if we have a definition for the specified global already.
20909467b48Spatrick   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
21009467b48Spatrick   if (!GV)
21109467b48Spatrick     GV = CreateGlobalCallback();
21209467b48Spatrick   assert(GV && "The CreateGlobalCallback is expected to create a global");
21309467b48Spatrick 
21409467b48Spatrick   // If the variable exists but has the wrong type, return a bitcast to the
21509467b48Spatrick   // right type.
21609467b48Spatrick   Type *GVTy = GV->getType();
21709467b48Spatrick   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
21809467b48Spatrick   if (GVTy != PTy)
21909467b48Spatrick     return ConstantExpr::getBitCast(GV, PTy);
22009467b48Spatrick 
22109467b48Spatrick   // Otherwise, we just found the existing function or a prototype.
22209467b48Spatrick   return GV;
22309467b48Spatrick }
22409467b48Spatrick 
22509467b48Spatrick // Overload to construct a global variable using its constructor's defaults.
getOrInsertGlobal(StringRef Name,Type * Ty)22609467b48Spatrick Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
22709467b48Spatrick   return getOrInsertGlobal(Name, Ty, [&] {
22809467b48Spatrick     return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
22909467b48Spatrick                               nullptr, Name);
23009467b48Spatrick   });
23109467b48Spatrick }
23209467b48Spatrick 
23309467b48Spatrick //===----------------------------------------------------------------------===//
23409467b48Spatrick // Methods for easy access to the global variables in the module.
23509467b48Spatrick //
23609467b48Spatrick 
23709467b48Spatrick // getNamedAlias - Look up the specified global in the module symbol table.
23809467b48Spatrick // If it does not exist, return null.
23909467b48Spatrick //
getNamedAlias(StringRef Name) const24009467b48Spatrick GlobalAlias *Module::getNamedAlias(StringRef Name) const {
24109467b48Spatrick   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
24209467b48Spatrick }
24309467b48Spatrick 
getNamedIFunc(StringRef Name) const24409467b48Spatrick GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
24509467b48Spatrick   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
24609467b48Spatrick }
24709467b48Spatrick 
24809467b48Spatrick /// getNamedMetadata - Return the first NamedMDNode in the module with the
24909467b48Spatrick /// specified name. This method returns null if a NamedMDNode with the
25009467b48Spatrick /// specified name is not found.
getNamedMetadata(const Twine & Name) const25109467b48Spatrick NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
25209467b48Spatrick   SmallString<256> NameData;
25309467b48Spatrick   StringRef NameRef = Name.toStringRef(NameData);
254097a140dSpatrick   return NamedMDSymTab.lookup(NameRef);
25509467b48Spatrick }
25609467b48Spatrick 
25709467b48Spatrick /// getOrInsertNamedMetadata - Return the first named MDNode in the module
25809467b48Spatrick /// with the specified name. This method returns a new NamedMDNode if a
25909467b48Spatrick /// NamedMDNode with the specified name is not found.
getOrInsertNamedMetadata(StringRef Name)26009467b48Spatrick NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
261097a140dSpatrick   NamedMDNode *&NMD = NamedMDSymTab[Name];
26209467b48Spatrick   if (!NMD) {
26309467b48Spatrick     NMD = new NamedMDNode(Name);
26409467b48Spatrick     NMD->setParent(this);
26509467b48Spatrick     NamedMDList.push_back(NMD);
26609467b48Spatrick   }
26709467b48Spatrick   return NMD;
26809467b48Spatrick }
26909467b48Spatrick 
27009467b48Spatrick /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
27109467b48Spatrick /// delete it.
eraseNamedMetadata(NamedMDNode * NMD)27209467b48Spatrick void Module::eraseNamedMetadata(NamedMDNode *NMD) {
273097a140dSpatrick   NamedMDSymTab.erase(NMD->getName());
27409467b48Spatrick   NamedMDList.erase(NMD->getIterator());
27509467b48Spatrick }
27609467b48Spatrick 
isValidModFlagBehavior(Metadata * MD,ModFlagBehavior & MFB)27709467b48Spatrick bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
27809467b48Spatrick   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
27909467b48Spatrick     uint64_t Val = Behavior->getLimitedValue();
28009467b48Spatrick     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
28109467b48Spatrick       MFB = static_cast<ModFlagBehavior>(Val);
28209467b48Spatrick       return true;
28309467b48Spatrick     }
28409467b48Spatrick   }
28509467b48Spatrick   return false;
28609467b48Spatrick }
28709467b48Spatrick 
isValidModuleFlag(const MDNode & ModFlag,ModFlagBehavior & MFB,MDString * & Key,Metadata * & Val)288097a140dSpatrick bool Module::isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB,
289097a140dSpatrick                                MDString *&Key, Metadata *&Val) {
290097a140dSpatrick   if (ModFlag.getNumOperands() < 3)
291097a140dSpatrick     return false;
292097a140dSpatrick   if (!isValidModFlagBehavior(ModFlag.getOperand(0), MFB))
293097a140dSpatrick     return false;
294097a140dSpatrick   MDString *K = dyn_cast_or_null<MDString>(ModFlag.getOperand(1));
295097a140dSpatrick   if (!K)
296097a140dSpatrick     return false;
297097a140dSpatrick   Key = K;
298097a140dSpatrick   Val = ModFlag.getOperand(2);
299097a140dSpatrick   return true;
300097a140dSpatrick }
301097a140dSpatrick 
30209467b48Spatrick /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
30309467b48Spatrick void Module::
getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> & Flags) const30409467b48Spatrick getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
30509467b48Spatrick   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
30609467b48Spatrick   if (!ModFlags) return;
30709467b48Spatrick 
30809467b48Spatrick   for (const MDNode *Flag : ModFlags->operands()) {
30909467b48Spatrick     ModFlagBehavior MFB;
310097a140dSpatrick     MDString *Key = nullptr;
311097a140dSpatrick     Metadata *Val = nullptr;
312097a140dSpatrick     if (isValidModuleFlag(*Flag, MFB, Key, Val)) {
31309467b48Spatrick       // Check the operands of the MDNode before accessing the operands.
31409467b48Spatrick       // The verifier will actually catch these failures.
31509467b48Spatrick       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
31609467b48Spatrick     }
31709467b48Spatrick   }
31809467b48Spatrick }
31909467b48Spatrick 
32009467b48Spatrick /// Return the corresponding value if Key appears in module flags, otherwise
32109467b48Spatrick /// return null.
getModuleFlag(StringRef Key) const32209467b48Spatrick Metadata *Module::getModuleFlag(StringRef Key) const {
32309467b48Spatrick   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
32409467b48Spatrick   getModuleFlagsMetadata(ModuleFlags);
32509467b48Spatrick   for (const ModuleFlagEntry &MFE : ModuleFlags) {
32609467b48Spatrick     if (Key == MFE.Key->getString())
32709467b48Spatrick       return MFE.Val;
32809467b48Spatrick   }
32909467b48Spatrick   return nullptr;
33009467b48Spatrick }
33109467b48Spatrick 
33209467b48Spatrick /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
33309467b48Spatrick /// represents module-level flags. This method returns null if there are no
33409467b48Spatrick /// module-level flags.
getModuleFlagsMetadata() const33509467b48Spatrick NamedMDNode *Module::getModuleFlagsMetadata() const {
33609467b48Spatrick   return getNamedMetadata("llvm.module.flags");
33709467b48Spatrick }
33809467b48Spatrick 
33909467b48Spatrick /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
34009467b48Spatrick /// represents module-level flags. If module-level flags aren't found, it
34109467b48Spatrick /// creates the named metadata that contains them.
getOrInsertModuleFlagsMetadata()34209467b48Spatrick NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
34309467b48Spatrick   return getOrInsertNamedMetadata("llvm.module.flags");
34409467b48Spatrick }
34509467b48Spatrick 
34609467b48Spatrick /// addModuleFlag - Add a module-level flag to the module-level flags
34709467b48Spatrick /// metadata. It will create the module-level flags named metadata if it doesn't
34809467b48Spatrick /// already exist.
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,Metadata * Val)34909467b48Spatrick void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
35009467b48Spatrick                            Metadata *Val) {
35109467b48Spatrick   Type *Int32Ty = Type::getInt32Ty(Context);
35209467b48Spatrick   Metadata *Ops[3] = {
35309467b48Spatrick       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
35409467b48Spatrick       MDString::get(Context, Key), Val};
35509467b48Spatrick   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
35609467b48Spatrick }
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,Constant * Val)35709467b48Spatrick void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
35809467b48Spatrick                            Constant *Val) {
35909467b48Spatrick   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
36009467b48Spatrick }
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,uint32_t Val)36109467b48Spatrick void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
36209467b48Spatrick                            uint32_t Val) {
36309467b48Spatrick   Type *Int32Ty = Type::getInt32Ty(Context);
36409467b48Spatrick   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
36509467b48Spatrick }
addModuleFlag(MDNode * Node)36609467b48Spatrick void Module::addModuleFlag(MDNode *Node) {
36709467b48Spatrick   assert(Node->getNumOperands() == 3 &&
36809467b48Spatrick          "Invalid number of operands for module flag!");
36909467b48Spatrick   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
37009467b48Spatrick          isa<MDString>(Node->getOperand(1)) &&
37109467b48Spatrick          "Invalid operand types for module flag!");
37209467b48Spatrick   getOrInsertModuleFlagsMetadata()->addOperand(Node);
37309467b48Spatrick }
37409467b48Spatrick 
setModuleFlag(ModFlagBehavior Behavior,StringRef Key,Metadata * Val)375097a140dSpatrick void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
376097a140dSpatrick                            Metadata *Val) {
377097a140dSpatrick   NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
378097a140dSpatrick   // Replace the flag if it already exists.
379097a140dSpatrick   for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
380097a140dSpatrick     MDNode *Flag = ModFlags->getOperand(I);
381097a140dSpatrick     ModFlagBehavior MFB;
382097a140dSpatrick     MDString *K = nullptr;
383097a140dSpatrick     Metadata *V = nullptr;
384097a140dSpatrick     if (isValidModuleFlag(*Flag, MFB, K, V) && K->getString() == Key) {
385097a140dSpatrick       Flag->replaceOperandWith(2, Val);
386097a140dSpatrick       return;
387097a140dSpatrick     }
388097a140dSpatrick   }
389097a140dSpatrick   addModuleFlag(Behavior, Key, Val);
390097a140dSpatrick }
391097a140dSpatrick 
setDataLayout(StringRef Desc)39209467b48Spatrick void Module::setDataLayout(StringRef Desc) {
39309467b48Spatrick   DL.reset(Desc);
39409467b48Spatrick }
39509467b48Spatrick 
setDataLayout(const DataLayout & Other)39609467b48Spatrick void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
39709467b48Spatrick 
getDataLayout() const39809467b48Spatrick const DataLayout &Module::getDataLayout() const { return DL; }
39909467b48Spatrick 
operator *() const40009467b48Spatrick DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
40109467b48Spatrick   return cast<DICompileUnit>(CUs->getOperand(Idx));
40209467b48Spatrick }
operator ->() const40309467b48Spatrick DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
40409467b48Spatrick   return cast<DICompileUnit>(CUs->getOperand(Idx));
40509467b48Spatrick }
40609467b48Spatrick 
SkipNoDebugCUs()40709467b48Spatrick void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
40809467b48Spatrick   while (CUs && (Idx < CUs->getNumOperands()) &&
40909467b48Spatrick          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
41009467b48Spatrick     ++Idx;
41109467b48Spatrick }
41209467b48Spatrick 
global_objects()41309467b48Spatrick iterator_range<Module::global_object_iterator> Module::global_objects() {
41409467b48Spatrick   return concat<GlobalObject>(functions(), globals());
41509467b48Spatrick }
41609467b48Spatrick iterator_range<Module::const_global_object_iterator>
global_objects() const41709467b48Spatrick Module::global_objects() const {
41809467b48Spatrick   return concat<const GlobalObject>(functions(), globals());
41909467b48Spatrick }
42009467b48Spatrick 
global_values()42109467b48Spatrick iterator_range<Module::global_value_iterator> Module::global_values() {
42209467b48Spatrick   return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
42309467b48Spatrick }
42409467b48Spatrick iterator_range<Module::const_global_value_iterator>
global_values() const42509467b48Spatrick Module::global_values() const {
42609467b48Spatrick   return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
42709467b48Spatrick }
42809467b48Spatrick 
42909467b48Spatrick //===----------------------------------------------------------------------===//
43009467b48Spatrick // Methods to control the materialization of GlobalValues in the Module.
43109467b48Spatrick //
setMaterializer(GVMaterializer * GVM)43209467b48Spatrick void Module::setMaterializer(GVMaterializer *GVM) {
43309467b48Spatrick   assert(!Materializer &&
43409467b48Spatrick          "Module already has a GVMaterializer.  Call materializeAll"
43509467b48Spatrick          " to clear it out before setting another one.");
43609467b48Spatrick   Materializer.reset(GVM);
43709467b48Spatrick }
43809467b48Spatrick 
materialize(GlobalValue * GV)43909467b48Spatrick Error Module::materialize(GlobalValue *GV) {
44009467b48Spatrick   if (!Materializer)
44109467b48Spatrick     return Error::success();
44209467b48Spatrick 
44309467b48Spatrick   return Materializer->materialize(GV);
44409467b48Spatrick }
44509467b48Spatrick 
materializeAll()44609467b48Spatrick Error Module::materializeAll() {
44709467b48Spatrick   if (!Materializer)
44809467b48Spatrick     return Error::success();
44909467b48Spatrick   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
45009467b48Spatrick   return M->materializeModule();
45109467b48Spatrick }
45209467b48Spatrick 
materializeMetadata()45309467b48Spatrick Error Module::materializeMetadata() {
45409467b48Spatrick   if (!Materializer)
45509467b48Spatrick     return Error::success();
45609467b48Spatrick   return Materializer->materializeMetadata();
45709467b48Spatrick }
45809467b48Spatrick 
45909467b48Spatrick //===----------------------------------------------------------------------===//
46009467b48Spatrick // Other module related stuff.
46109467b48Spatrick //
46209467b48Spatrick 
getIdentifiedStructTypes() const46309467b48Spatrick std::vector<StructType *> Module::getIdentifiedStructTypes() const {
46409467b48Spatrick   // If we have a materializer, it is possible that some unread function
46509467b48Spatrick   // uses a type that is currently not visible to a TypeFinder, so ask
46609467b48Spatrick   // the materializer which types it created.
46709467b48Spatrick   if (Materializer)
46809467b48Spatrick     return Materializer->getIdentifiedStructTypes();
46909467b48Spatrick 
47009467b48Spatrick   std::vector<StructType *> Ret;
47109467b48Spatrick   TypeFinder SrcStructTypes;
47209467b48Spatrick   SrcStructTypes.run(*this, true);
47309467b48Spatrick   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
47409467b48Spatrick   return Ret;
47509467b48Spatrick }
47609467b48Spatrick 
getUniqueIntrinsicName(StringRef BaseName,Intrinsic::ID Id,const FunctionType * Proto)47773471bf0Spatrick std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
47873471bf0Spatrick                                            const FunctionType *Proto) {
47973471bf0Spatrick   auto Encode = [&BaseName](unsigned Suffix) {
48073471bf0Spatrick     return (Twine(BaseName) + "." + Twine(Suffix)).str();
48173471bf0Spatrick   };
48273471bf0Spatrick 
48373471bf0Spatrick   {
48473471bf0Spatrick     // fast path - the prototype is already known
48573471bf0Spatrick     auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
48673471bf0Spatrick     if (!UinItInserted.second)
48773471bf0Spatrick       return Encode(UinItInserted.first->second);
48873471bf0Spatrick   }
48973471bf0Spatrick 
49073471bf0Spatrick   // Not known yet. A new entry was created with index 0. Check if there already
49173471bf0Spatrick   // exists a matching declaration, or select a new entry.
49273471bf0Spatrick 
49373471bf0Spatrick   // Start looking for names with the current known maximum count (or 0).
49473471bf0Spatrick   auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
49573471bf0Spatrick   unsigned Count = NiidItInserted.first->second;
49673471bf0Spatrick 
49773471bf0Spatrick   // This might be slow if a whole population of intrinsics already existed, but
49873471bf0Spatrick   // we cache the values for later usage.
49973471bf0Spatrick   std::string NewName;
50073471bf0Spatrick   while (true) {
50173471bf0Spatrick     NewName = Encode(Count);
50273471bf0Spatrick     GlobalValue *F = getNamedValue(NewName);
50373471bf0Spatrick     if (!F) {
50473471bf0Spatrick       // Reserve this entry for the new proto
50573471bf0Spatrick       UniquedIntrinsicNames[{Id, Proto}] = Count;
50673471bf0Spatrick       break;
50773471bf0Spatrick     }
50873471bf0Spatrick 
50973471bf0Spatrick     // A declaration with this name already exists. Remember it.
51073471bf0Spatrick     FunctionType *FT = dyn_cast<FunctionType>(F->getValueType());
51173471bf0Spatrick     auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
51273471bf0Spatrick     if (FT == Proto) {
51373471bf0Spatrick       // It was a declaration for our prototype. This entry was allocated in the
51473471bf0Spatrick       // beginning. Update the count to match the existing declaration.
51573471bf0Spatrick       UinItInserted.first->second = Count;
51673471bf0Spatrick       break;
51773471bf0Spatrick     }
51873471bf0Spatrick 
51973471bf0Spatrick     ++Count;
52073471bf0Spatrick   }
52173471bf0Spatrick 
52273471bf0Spatrick   NiidItInserted.first->second = Count + 1;
52373471bf0Spatrick 
52473471bf0Spatrick   return NewName;
52573471bf0Spatrick }
52673471bf0Spatrick 
52709467b48Spatrick // dropAllReferences() - This function causes all the subelements to "let go"
52809467b48Spatrick // of all references that they are maintaining.  This allows one to 'delete' a
52909467b48Spatrick // whole module at a time, even though there may be circular references... first
53009467b48Spatrick // all references are dropped, and all use counts go to zero.  Then everything
53109467b48Spatrick // is deleted for real.  Note that no operations are valid on an object that
53209467b48Spatrick // has "dropped all references", except operator delete.
53309467b48Spatrick //
dropAllReferences()53409467b48Spatrick void Module::dropAllReferences() {
53509467b48Spatrick   for (Function &F : *this)
53609467b48Spatrick     F.dropAllReferences();
53709467b48Spatrick 
53809467b48Spatrick   for (GlobalVariable &GV : globals())
53909467b48Spatrick     GV.dropAllReferences();
54009467b48Spatrick 
54109467b48Spatrick   for (GlobalAlias &GA : aliases())
54209467b48Spatrick     GA.dropAllReferences();
54309467b48Spatrick 
54409467b48Spatrick   for (GlobalIFunc &GIF : ifuncs())
54509467b48Spatrick     GIF.dropAllReferences();
54609467b48Spatrick }
54709467b48Spatrick 
getNumberRegisterParameters() const54809467b48Spatrick unsigned Module::getNumberRegisterParameters() const {
54909467b48Spatrick   auto *Val =
55009467b48Spatrick       cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
55109467b48Spatrick   if (!Val)
55209467b48Spatrick     return 0;
55309467b48Spatrick   return cast<ConstantInt>(Val->getValue())->getZExtValue();
55409467b48Spatrick }
55509467b48Spatrick 
getDwarfVersion() const55609467b48Spatrick unsigned Module::getDwarfVersion() const {
55709467b48Spatrick   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
55809467b48Spatrick   if (!Val)
55909467b48Spatrick     return 0;
56009467b48Spatrick   return cast<ConstantInt>(Val->getValue())->getZExtValue();
56109467b48Spatrick }
56209467b48Spatrick 
isDwarf64() const56373471bf0Spatrick bool Module::isDwarf64() const {
56473471bf0Spatrick   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64"));
56573471bf0Spatrick   return Val && cast<ConstantInt>(Val->getValue())->isOne();
56673471bf0Spatrick }
56773471bf0Spatrick 
getCodeViewFlag() const56809467b48Spatrick unsigned Module::getCodeViewFlag() const {
56909467b48Spatrick   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
57009467b48Spatrick   if (!Val)
57109467b48Spatrick     return 0;
57209467b48Spatrick   return cast<ConstantInt>(Val->getValue())->getZExtValue();
57309467b48Spatrick }
57409467b48Spatrick 
getInstructionCount() const57573471bf0Spatrick unsigned Module::getInstructionCount() const {
57609467b48Spatrick   unsigned NumInstrs = 0;
57773471bf0Spatrick   for (const Function &F : FunctionList)
57809467b48Spatrick     NumInstrs += F.getInstructionCount();
57909467b48Spatrick   return NumInstrs;
58009467b48Spatrick }
58109467b48Spatrick 
getOrInsertComdat(StringRef Name)58209467b48Spatrick Comdat *Module::getOrInsertComdat(StringRef Name) {
58309467b48Spatrick   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
58409467b48Spatrick   Entry.second.Name = &Entry;
58509467b48Spatrick   return &Entry.second;
58609467b48Spatrick }
58709467b48Spatrick 
getPICLevel() const58809467b48Spatrick PICLevel::Level Module::getPICLevel() const {
58909467b48Spatrick   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
59009467b48Spatrick 
59109467b48Spatrick   if (!Val)
59209467b48Spatrick     return PICLevel::NotPIC;
59309467b48Spatrick 
59409467b48Spatrick   return static_cast<PICLevel::Level>(
59509467b48Spatrick       cast<ConstantInt>(Val->getValue())->getZExtValue());
59609467b48Spatrick }
59709467b48Spatrick 
setPICLevel(PICLevel::Level PL)59809467b48Spatrick void Module::setPICLevel(PICLevel::Level PL) {
599*d415bd75Srobert   // The merge result of a non-PIC object and a PIC object can only be reliably
600*d415bd75Srobert   // used as a non-PIC object, so use the Min merge behavior.
601*d415bd75Srobert   addModuleFlag(ModFlagBehavior::Min, "PIC Level", PL);
60209467b48Spatrick }
60309467b48Spatrick 
getPIELevel() const60409467b48Spatrick PIELevel::Level Module::getPIELevel() const {
60509467b48Spatrick   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
60609467b48Spatrick 
60709467b48Spatrick   if (!Val)
60809467b48Spatrick     return PIELevel::Default;
60909467b48Spatrick 
61009467b48Spatrick   return static_cast<PIELevel::Level>(
61109467b48Spatrick       cast<ConstantInt>(Val->getValue())->getZExtValue());
61209467b48Spatrick }
61309467b48Spatrick 
setPIELevel(PIELevel::Level PL)61409467b48Spatrick void Module::setPIELevel(PIELevel::Level PL) {
61509467b48Spatrick   addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
61609467b48Spatrick }
61709467b48Spatrick 
getCodeModel() const618*d415bd75Srobert std::optional<CodeModel::Model> Module::getCodeModel() const {
61909467b48Spatrick   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
62009467b48Spatrick 
62109467b48Spatrick   if (!Val)
622*d415bd75Srobert     return std::nullopt;
62309467b48Spatrick 
62409467b48Spatrick   return static_cast<CodeModel::Model>(
62509467b48Spatrick       cast<ConstantInt>(Val->getValue())->getZExtValue());
62609467b48Spatrick }
62709467b48Spatrick 
setCodeModel(CodeModel::Model CL)62809467b48Spatrick void Module::setCodeModel(CodeModel::Model CL) {
62909467b48Spatrick   // Linking object files with different code models is undefined behavior
63009467b48Spatrick   // because the compiler would have to generate additional code (to span
63109467b48Spatrick   // longer jumps) if a larger code model is used with a smaller one.
63209467b48Spatrick   // Therefore we will treat attempts to mix code models as an error.
63309467b48Spatrick   addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
63409467b48Spatrick }
63509467b48Spatrick 
setProfileSummary(Metadata * M,ProfileSummary::Kind Kind)63609467b48Spatrick void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
63709467b48Spatrick   if (Kind == ProfileSummary::PSK_CSInstr)
638097a140dSpatrick     setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
63909467b48Spatrick   else
640097a140dSpatrick     setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
64109467b48Spatrick }
64209467b48Spatrick 
getProfileSummary(bool IsCS) const64373471bf0Spatrick Metadata *Module::getProfileSummary(bool IsCS) const {
64409467b48Spatrick   return (IsCS ? getModuleFlag("CSProfileSummary")
64509467b48Spatrick                : getModuleFlag("ProfileSummary"));
64609467b48Spatrick }
64709467b48Spatrick 
getSemanticInterposition() const648097a140dSpatrick bool Module::getSemanticInterposition() const {
649097a140dSpatrick   Metadata *MF = getModuleFlag("SemanticInterposition");
650097a140dSpatrick 
651097a140dSpatrick   auto *Val = cast_or_null<ConstantAsMetadata>(MF);
652097a140dSpatrick   if (!Val)
653097a140dSpatrick     return false;
654097a140dSpatrick 
655097a140dSpatrick   return cast<ConstantInt>(Val->getValue())->getZExtValue();
656097a140dSpatrick }
657097a140dSpatrick 
setSemanticInterposition(bool SI)658097a140dSpatrick void Module::setSemanticInterposition(bool SI) {
659097a140dSpatrick   addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI);
660097a140dSpatrick }
661097a140dSpatrick 
setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB)66209467b48Spatrick void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
66309467b48Spatrick   OwnedMemoryBuffer = std::move(MB);
66409467b48Spatrick }
66509467b48Spatrick 
getRtLibUseGOT() const66609467b48Spatrick bool Module::getRtLibUseGOT() const {
66709467b48Spatrick   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
66809467b48Spatrick   return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
66909467b48Spatrick }
67009467b48Spatrick 
setRtLibUseGOT()67109467b48Spatrick void Module::setRtLibUseGOT() {
67209467b48Spatrick   addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
67309467b48Spatrick }
67409467b48Spatrick 
getUwtable() const675*d415bd75Srobert UWTableKind Module::getUwtable() const {
676*d415bd75Srobert   if (auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable")))
677*d415bd75Srobert     return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue());
678*d415bd75Srobert   return UWTableKind::None;
67973471bf0Spatrick }
68073471bf0Spatrick 
setUwtable(UWTableKind Kind)681*d415bd75Srobert void Module::setUwtable(UWTableKind Kind) {
682*d415bd75Srobert   addModuleFlag(ModFlagBehavior::Max, "uwtable", uint32_t(Kind));
683*d415bd75Srobert }
68473471bf0Spatrick 
getFramePointer() const68573471bf0Spatrick FramePointerKind Module::getFramePointer() const {
68673471bf0Spatrick   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer"));
68773471bf0Spatrick   return static_cast<FramePointerKind>(
68873471bf0Spatrick       Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
68973471bf0Spatrick }
69073471bf0Spatrick 
setFramePointer(FramePointerKind Kind)69173471bf0Spatrick void Module::setFramePointer(FramePointerKind Kind) {
69273471bf0Spatrick   addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind));
69373471bf0Spatrick }
69473471bf0Spatrick 
getStackProtectorGuard() const69573471bf0Spatrick StringRef Module::getStackProtectorGuard() const {
69673471bf0Spatrick   Metadata *MD = getModuleFlag("stack-protector-guard");
69773471bf0Spatrick   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
69873471bf0Spatrick     return MDS->getString();
69973471bf0Spatrick   return {};
70073471bf0Spatrick }
70173471bf0Spatrick 
setStackProtectorGuard(StringRef Kind)70273471bf0Spatrick void Module::setStackProtectorGuard(StringRef Kind) {
70373471bf0Spatrick   MDString *ID = MDString::get(getContext(), Kind);
70473471bf0Spatrick   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID);
70573471bf0Spatrick }
70673471bf0Spatrick 
getStackProtectorGuardReg() const70773471bf0Spatrick StringRef Module::getStackProtectorGuardReg() const {
70873471bf0Spatrick   Metadata *MD = getModuleFlag("stack-protector-guard-reg");
70973471bf0Spatrick   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
71073471bf0Spatrick     return MDS->getString();
71173471bf0Spatrick   return {};
71273471bf0Spatrick }
71373471bf0Spatrick 
setStackProtectorGuardReg(StringRef Reg)71473471bf0Spatrick void Module::setStackProtectorGuardReg(StringRef Reg) {
71573471bf0Spatrick   MDString *ID = MDString::get(getContext(), Reg);
71673471bf0Spatrick   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID);
71773471bf0Spatrick }
71873471bf0Spatrick 
getStackProtectorGuardSymbol() const719*d415bd75Srobert StringRef Module::getStackProtectorGuardSymbol() const {
720*d415bd75Srobert   Metadata *MD = getModuleFlag("stack-protector-guard-symbol");
721*d415bd75Srobert   if (auto *MDS = dyn_cast_or_null<MDString>(MD))
722*d415bd75Srobert     return MDS->getString();
723*d415bd75Srobert   return {};
724*d415bd75Srobert }
725*d415bd75Srobert 
setStackProtectorGuardSymbol(StringRef Symbol)726*d415bd75Srobert void Module::setStackProtectorGuardSymbol(StringRef Symbol) {
727*d415bd75Srobert   MDString *ID = MDString::get(getContext(), Symbol);
728*d415bd75Srobert   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-symbol", ID);
729*d415bd75Srobert }
730*d415bd75Srobert 
getStackProtectorGuardOffset() const73173471bf0Spatrick int Module::getStackProtectorGuardOffset() const {
73273471bf0Spatrick   Metadata *MD = getModuleFlag("stack-protector-guard-offset");
73373471bf0Spatrick   if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
73473471bf0Spatrick     return CI->getSExtValue();
73573471bf0Spatrick   return INT_MAX;
73673471bf0Spatrick }
73773471bf0Spatrick 
setStackProtectorGuardOffset(int Offset)73873471bf0Spatrick void Module::setStackProtectorGuardOffset(int Offset) {
73973471bf0Spatrick   addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset);
74073471bf0Spatrick }
74173471bf0Spatrick 
getOverrideStackAlignment() const74273471bf0Spatrick unsigned Module::getOverrideStackAlignment() const {
74373471bf0Spatrick   Metadata *MD = getModuleFlag("override-stack-alignment");
74473471bf0Spatrick   if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
74573471bf0Spatrick     return CI->getZExtValue();
74673471bf0Spatrick   return 0;
74773471bf0Spatrick }
74873471bf0Spatrick 
setOverrideStackAlignment(unsigned Align)74973471bf0Spatrick void Module::setOverrideStackAlignment(unsigned Align) {
75073471bf0Spatrick   addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align);
75173471bf0Spatrick }
75273471bf0Spatrick 
addSDKVersionMD(const VersionTuple & V,Module & M,StringRef Name)753*d415bd75Srobert static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name) {
75409467b48Spatrick   SmallVector<unsigned, 3> Entries;
75509467b48Spatrick   Entries.push_back(V.getMajor());
75609467b48Spatrick   if (auto Minor = V.getMinor()) {
75709467b48Spatrick     Entries.push_back(*Minor);
75809467b48Spatrick     if (auto Subminor = V.getSubminor())
75909467b48Spatrick       Entries.push_back(*Subminor);
76009467b48Spatrick     // Ignore the 'build' component as it can't be represented in the object
76109467b48Spatrick     // file.
76209467b48Spatrick   }
763*d415bd75Srobert   M.addModuleFlag(Module::ModFlagBehavior::Warning, Name,
764*d415bd75Srobert                   ConstantDataArray::get(M.getContext(), Entries));
76509467b48Spatrick }
76609467b48Spatrick 
setSDKVersion(const VersionTuple & V)767*d415bd75Srobert void Module::setSDKVersion(const VersionTuple &V) {
768*d415bd75Srobert   addSDKVersionMD(V, *this, "SDK Version");
769*d415bd75Srobert }
770*d415bd75Srobert 
getSDKVersionMD(Metadata * MD)771*d415bd75Srobert static VersionTuple getSDKVersionMD(Metadata *MD) {
772*d415bd75Srobert   auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD);
77309467b48Spatrick   if (!CM)
77409467b48Spatrick     return {};
77509467b48Spatrick   auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
77609467b48Spatrick   if (!Arr)
77709467b48Spatrick     return {};
778*d415bd75Srobert   auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> {
77909467b48Spatrick     if (Index >= Arr->getNumElements())
780*d415bd75Srobert       return std::nullopt;
78109467b48Spatrick     return (unsigned)Arr->getElementAsInteger(Index);
78209467b48Spatrick   };
78309467b48Spatrick   auto Major = getVersionComponent(0);
78409467b48Spatrick   if (!Major)
78509467b48Spatrick     return {};
78609467b48Spatrick   VersionTuple Result = VersionTuple(*Major);
78709467b48Spatrick   if (auto Minor = getVersionComponent(1)) {
78809467b48Spatrick     Result = VersionTuple(*Major, *Minor);
78909467b48Spatrick     if (auto Subminor = getVersionComponent(2)) {
79009467b48Spatrick       Result = VersionTuple(*Major, *Minor, *Subminor);
79109467b48Spatrick     }
79209467b48Spatrick   }
79309467b48Spatrick   return Result;
79409467b48Spatrick }
79509467b48Spatrick 
getSDKVersion() const796*d415bd75Srobert VersionTuple Module::getSDKVersion() const {
797*d415bd75Srobert   return getSDKVersionMD(getModuleFlag("SDK Version"));
798*d415bd75Srobert }
799*d415bd75Srobert 
collectUsedGlobalVariables(const Module & M,SmallVectorImpl<GlobalValue * > & Vec,bool CompilerUsed)80009467b48Spatrick GlobalVariable *llvm::collectUsedGlobalVariables(
80173471bf0Spatrick     const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
80209467b48Spatrick   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
80309467b48Spatrick   GlobalVariable *GV = M.getGlobalVariable(Name);
80409467b48Spatrick   if (!GV || !GV->hasInitializer())
80509467b48Spatrick     return GV;
80609467b48Spatrick 
80709467b48Spatrick   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
80809467b48Spatrick   for (Value *Op : Init->operands()) {
80909467b48Spatrick     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
81073471bf0Spatrick     Vec.push_back(G);
81109467b48Spatrick   }
81209467b48Spatrick   return GV;
81309467b48Spatrick }
814097a140dSpatrick 
setPartialSampleProfileRatio(const ModuleSummaryIndex & Index)815097a140dSpatrick void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) {
816097a140dSpatrick   if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
817097a140dSpatrick     std::unique_ptr<ProfileSummary> ProfileSummary(
818097a140dSpatrick         ProfileSummary::getFromMD(SummaryMD));
819097a140dSpatrick     if (ProfileSummary) {
820097a140dSpatrick       if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample ||
821097a140dSpatrick           !ProfileSummary->isPartialProfile())
822097a140dSpatrick         return;
823097a140dSpatrick       uint64_t BlockCount = Index.getBlockCount();
824097a140dSpatrick       uint32_t NumCounts = ProfileSummary->getNumCounts();
825097a140dSpatrick       if (!NumCounts)
826097a140dSpatrick         return;
827097a140dSpatrick       double Ratio = (double)BlockCount / NumCounts;
828097a140dSpatrick       ProfileSummary->setPartialProfileRatio(Ratio);
829097a140dSpatrick       setProfileSummary(ProfileSummary->getMD(getContext()),
830097a140dSpatrick                         ProfileSummary::PSK_Sample);
831097a140dSpatrick     }
832097a140dSpatrick   }
833097a140dSpatrick }
834*d415bd75Srobert 
getDarwinTargetVariantTriple() const835*d415bd75Srobert StringRef Module::getDarwinTargetVariantTriple() const {
836*d415bd75Srobert   if (const auto *MD = getModuleFlag("darwin.target_variant.triple"))
837*d415bd75Srobert     return cast<MDString>(MD)->getString();
838*d415bd75Srobert   return "";
839*d415bd75Srobert }
840*d415bd75Srobert 
setDarwinTargetVariantTriple(StringRef T)841*d415bd75Srobert void Module::setDarwinTargetVariantTriple(StringRef T) {
842*d415bd75Srobert   addModuleFlag(ModFlagBehavior::Override, "darwin.target_variant.triple",
843*d415bd75Srobert                 MDString::get(getContext(), T));
844*d415bd75Srobert }
845*d415bd75Srobert 
getDarwinTargetVariantSDKVersion() const846*d415bd75Srobert VersionTuple Module::getDarwinTargetVariantSDKVersion() const {
847*d415bd75Srobert   return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version"));
848*d415bd75Srobert }
849*d415bd75Srobert 
setDarwinTargetVariantSDKVersion(VersionTuple Version)850*d415bd75Srobert void Module::setDarwinTargetVariantSDKVersion(VersionTuple Version) {
851*d415bd75Srobert   addSDKVersionMD(Version, *this, "darwin.target_variant.SDK Version");
852*d415bd75Srobert }
853