17330f729Sjoerg //===- Module.cpp - Implement the Module class ----------------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file implements the Module class for the IR library.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg
137330f729Sjoerg #include "llvm/IR/Module.h"
147330f729Sjoerg #include "SymbolTableListTraitsImpl.h"
157330f729Sjoerg #include "llvm/ADT/Optional.h"
167330f729Sjoerg #include "llvm/ADT/SmallPtrSet.h"
177330f729Sjoerg #include "llvm/ADT/SmallString.h"
187330f729Sjoerg #include "llvm/ADT/SmallVector.h"
197330f729Sjoerg #include "llvm/ADT/StringMap.h"
207330f729Sjoerg #include "llvm/ADT/StringRef.h"
217330f729Sjoerg #include "llvm/ADT/Twine.h"
227330f729Sjoerg #include "llvm/IR/Attributes.h"
237330f729Sjoerg #include "llvm/IR/Comdat.h"
247330f729Sjoerg #include "llvm/IR/Constants.h"
257330f729Sjoerg #include "llvm/IR/DataLayout.h"
267330f729Sjoerg #include "llvm/IR/DebugInfoMetadata.h"
277330f729Sjoerg #include "llvm/IR/DerivedTypes.h"
287330f729Sjoerg #include "llvm/IR/Function.h"
297330f729Sjoerg #include "llvm/IR/GVMaterializer.h"
307330f729Sjoerg #include "llvm/IR/GlobalAlias.h"
317330f729Sjoerg #include "llvm/IR/GlobalIFunc.h"
327330f729Sjoerg #include "llvm/IR/GlobalValue.h"
337330f729Sjoerg #include "llvm/IR/GlobalVariable.h"
347330f729Sjoerg #include "llvm/IR/LLVMContext.h"
357330f729Sjoerg #include "llvm/IR/Metadata.h"
36*82d56013Sjoerg #include "llvm/IR/ModuleSummaryIndex.h"
377330f729Sjoerg #include "llvm/IR/SymbolTableListTraits.h"
387330f729Sjoerg #include "llvm/IR/Type.h"
397330f729Sjoerg #include "llvm/IR/TypeFinder.h"
407330f729Sjoerg #include "llvm/IR/Value.h"
417330f729Sjoerg #include "llvm/IR/ValueSymbolTable.h"
427330f729Sjoerg #include "llvm/Pass.h"
437330f729Sjoerg #include "llvm/Support/Casting.h"
447330f729Sjoerg #include "llvm/Support/CodeGen.h"
457330f729Sjoerg #include "llvm/Support/Error.h"
467330f729Sjoerg #include "llvm/Support/MemoryBuffer.h"
477330f729Sjoerg #include "llvm/Support/Path.h"
487330f729Sjoerg #include "llvm/Support/RandomNumberGenerator.h"
497330f729Sjoerg #include "llvm/Support/VersionTuple.h"
507330f729Sjoerg #include <algorithm>
517330f729Sjoerg #include <cassert>
527330f729Sjoerg #include <cstdint>
537330f729Sjoerg #include <memory>
547330f729Sjoerg #include <utility>
557330f729Sjoerg #include <vector>
567330f729Sjoerg
577330f729Sjoerg using namespace llvm;
587330f729Sjoerg
597330f729Sjoerg //===----------------------------------------------------------------------===//
607330f729Sjoerg // Methods to implement the globals and functions lists.
617330f729Sjoerg //
627330f729Sjoerg
637330f729Sjoerg // Explicit instantiations of SymbolTableListTraits since some of the methods
647330f729Sjoerg // are not in the public header file.
657330f729Sjoerg template class llvm::SymbolTableListTraits<Function>;
667330f729Sjoerg template class llvm::SymbolTableListTraits<GlobalVariable>;
677330f729Sjoerg template class llvm::SymbolTableListTraits<GlobalAlias>;
687330f729Sjoerg template class llvm::SymbolTableListTraits<GlobalIFunc>;
697330f729Sjoerg
707330f729Sjoerg //===----------------------------------------------------------------------===//
717330f729Sjoerg // Primitive Module methods.
727330f729Sjoerg //
737330f729Sjoerg
Module(StringRef MID,LLVMContext & C)747330f729Sjoerg Module::Module(StringRef MID, LLVMContext &C)
75*82d56013Sjoerg : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>()),
76*82d56013Sjoerg Materializer(), ModuleID(std::string(MID)),
77*82d56013Sjoerg SourceFileName(std::string(MID)), DL("") {
787330f729Sjoerg Context.addModule(this);
797330f729Sjoerg }
807330f729Sjoerg
~Module()817330f729Sjoerg Module::~Module() {
827330f729Sjoerg Context.removeModule(this);
837330f729Sjoerg dropAllReferences();
847330f729Sjoerg GlobalList.clear();
857330f729Sjoerg FunctionList.clear();
867330f729Sjoerg AliasList.clear();
877330f729Sjoerg IFuncList.clear();
887330f729Sjoerg }
897330f729Sjoerg
90*82d56013Sjoerg std::unique_ptr<RandomNumberGenerator>
createRNG(const StringRef Name) const91*82d56013Sjoerg Module::createRNG(const StringRef Name) const {
92*82d56013Sjoerg SmallString<32> Salt(Name);
937330f729Sjoerg
947330f729Sjoerg // This RNG is guaranteed to produce the same random stream only
957330f729Sjoerg // when the Module ID and thus the input filename is the same. This
967330f729Sjoerg // might be problematic if the input filename extension changes
977330f729Sjoerg // (e.g. from .c to .bc or .ll).
987330f729Sjoerg //
997330f729Sjoerg // We could store this salt in NamedMetadata, but this would make
1007330f729Sjoerg // the parameter non-const. This would unfortunately make this
1017330f729Sjoerg // interface unusable by any Machine passes, since they only have a
1027330f729Sjoerg // const reference to their IR Module. Alternatively we can always
1037330f729Sjoerg // store salt metadata from the Module constructor.
1047330f729Sjoerg Salt += sys::path::filename(getModuleIdentifier());
1057330f729Sjoerg
106*82d56013Sjoerg return std::unique_ptr<RandomNumberGenerator>(
107*82d56013Sjoerg new RandomNumberGenerator(Salt));
1087330f729Sjoerg }
1097330f729Sjoerg
1107330f729Sjoerg /// getNamedValue - Return the first global value in the module with
1117330f729Sjoerg /// the specified name, of arbitrary type. This method returns null
1127330f729Sjoerg /// if a global with the specified name is not found.
getNamedValue(StringRef Name) const1137330f729Sjoerg GlobalValue *Module::getNamedValue(StringRef Name) const {
1147330f729Sjoerg return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
1157330f729Sjoerg }
1167330f729Sjoerg
1177330f729Sjoerg /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
1187330f729Sjoerg /// This ID is uniqued across modules in the current LLVMContext.
getMDKindID(StringRef Name) const1197330f729Sjoerg unsigned Module::getMDKindID(StringRef Name) const {
1207330f729Sjoerg return Context.getMDKindID(Name);
1217330f729Sjoerg }
1227330f729Sjoerg
1237330f729Sjoerg /// getMDKindNames - Populate client supplied SmallVector with the name for
1247330f729Sjoerg /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
1257330f729Sjoerg /// so it is filled in as an empty string.
getMDKindNames(SmallVectorImpl<StringRef> & Result) const1267330f729Sjoerg void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
1277330f729Sjoerg return Context.getMDKindNames(Result);
1287330f729Sjoerg }
1297330f729Sjoerg
getOperandBundleTags(SmallVectorImpl<StringRef> & Result) const1307330f729Sjoerg void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
1317330f729Sjoerg return Context.getOperandBundleTags(Result);
1327330f729Sjoerg }
1337330f729Sjoerg
1347330f729Sjoerg //===----------------------------------------------------------------------===//
1357330f729Sjoerg // Methods for easy access to the functions in the module.
1367330f729Sjoerg //
1377330f729Sjoerg
1387330f729Sjoerg // getOrInsertFunction - Look up the specified function in the module symbol
1397330f729Sjoerg // table. If it does not exist, add a prototype for the function and return
1407330f729Sjoerg // it. This is nice because it allows most passes to get away with not handling
1417330f729Sjoerg // the symbol table directly for this common task.
1427330f729Sjoerg //
getOrInsertFunction(StringRef Name,FunctionType * Ty,AttributeList AttributeList)1437330f729Sjoerg FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
1447330f729Sjoerg AttributeList AttributeList) {
1457330f729Sjoerg // See if we have a definition for the specified function already.
1467330f729Sjoerg GlobalValue *F = getNamedValue(Name);
1477330f729Sjoerg if (!F) {
1487330f729Sjoerg // Nope, add it
1497330f729Sjoerg Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
1507330f729Sjoerg DL.getProgramAddressSpace(), Name);
1517330f729Sjoerg if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
1527330f729Sjoerg New->setAttributes(AttributeList);
1537330f729Sjoerg FunctionList.push_back(New);
1547330f729Sjoerg return {Ty, New}; // Return the new prototype.
1557330f729Sjoerg }
1567330f729Sjoerg
1577330f729Sjoerg // If the function exists but has the wrong type, return a bitcast to the
1587330f729Sjoerg // right type.
1597330f729Sjoerg auto *PTy = PointerType::get(Ty, F->getAddressSpace());
1607330f729Sjoerg if (F->getType() != PTy)
1617330f729Sjoerg return {Ty, ConstantExpr::getBitCast(F, PTy)};
1627330f729Sjoerg
1637330f729Sjoerg // Otherwise, we just found the existing function or a prototype.
1647330f729Sjoerg return {Ty, F};
1657330f729Sjoerg }
1667330f729Sjoerg
getOrInsertFunction(StringRef Name,FunctionType * Ty)1677330f729Sjoerg FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
1687330f729Sjoerg return getOrInsertFunction(Name, Ty, AttributeList());
1697330f729Sjoerg }
1707330f729Sjoerg
1717330f729Sjoerg // getFunction - Look up the specified function in the module symbol table.
1727330f729Sjoerg // If it does not exist, return null.
1737330f729Sjoerg //
getFunction(StringRef Name) const1747330f729Sjoerg Function *Module::getFunction(StringRef Name) const {
1757330f729Sjoerg return dyn_cast_or_null<Function>(getNamedValue(Name));
1767330f729Sjoerg }
1777330f729Sjoerg
1787330f729Sjoerg //===----------------------------------------------------------------------===//
1797330f729Sjoerg // Methods for easy access to the global variables in the module.
1807330f729Sjoerg //
1817330f729Sjoerg
1827330f729Sjoerg /// getGlobalVariable - Look up the specified global variable in the module
1837330f729Sjoerg /// symbol table. If it does not exist, return null. The type argument
1847330f729Sjoerg /// should be the underlying type of the global, i.e., it should not have
1857330f729Sjoerg /// the top-level PointerType, which represents the address of the global.
1867330f729Sjoerg /// If AllowLocal is set to true, this function will return types that
1877330f729Sjoerg /// have an local. By default, these types are not returned.
1887330f729Sjoerg ///
getGlobalVariable(StringRef Name,bool AllowLocal) const1897330f729Sjoerg GlobalVariable *Module::getGlobalVariable(StringRef Name,
1907330f729Sjoerg bool AllowLocal) const {
1917330f729Sjoerg if (GlobalVariable *Result =
1927330f729Sjoerg dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
1937330f729Sjoerg if (AllowLocal || !Result->hasLocalLinkage())
1947330f729Sjoerg return Result;
1957330f729Sjoerg return nullptr;
1967330f729Sjoerg }
1977330f729Sjoerg
1987330f729Sjoerg /// getOrInsertGlobal - Look up the specified global in the module symbol table.
1997330f729Sjoerg /// 1. If it does not exist, add a declaration of the global and return it.
2007330f729Sjoerg /// 2. Else, the global exists but has the wrong type: return the function
2017330f729Sjoerg /// with a constantexpr cast to the right type.
2027330f729Sjoerg /// 3. Finally, if the existing global is the correct declaration, return the
2037330f729Sjoerg /// existing global.
getOrInsertGlobal(StringRef Name,Type * Ty,function_ref<GlobalVariable * ()> CreateGlobalCallback)2047330f729Sjoerg Constant *Module::getOrInsertGlobal(
2057330f729Sjoerg StringRef Name, Type *Ty,
2067330f729Sjoerg function_ref<GlobalVariable *()> CreateGlobalCallback) {
2077330f729Sjoerg // See if we have a definition for the specified global already.
2087330f729Sjoerg GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
2097330f729Sjoerg if (!GV)
2107330f729Sjoerg GV = CreateGlobalCallback();
2117330f729Sjoerg assert(GV && "The CreateGlobalCallback is expected to create a global");
2127330f729Sjoerg
2137330f729Sjoerg // If the variable exists but has the wrong type, return a bitcast to the
2147330f729Sjoerg // right type.
2157330f729Sjoerg Type *GVTy = GV->getType();
2167330f729Sjoerg PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
2177330f729Sjoerg if (GVTy != PTy)
2187330f729Sjoerg return ConstantExpr::getBitCast(GV, PTy);
2197330f729Sjoerg
2207330f729Sjoerg // Otherwise, we just found the existing function or a prototype.
2217330f729Sjoerg return GV;
2227330f729Sjoerg }
2237330f729Sjoerg
2247330f729Sjoerg // Overload to construct a global variable using its constructor's defaults.
getOrInsertGlobal(StringRef Name,Type * Ty)2257330f729Sjoerg Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
2267330f729Sjoerg return getOrInsertGlobal(Name, Ty, [&] {
2277330f729Sjoerg return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
2287330f729Sjoerg nullptr, Name);
2297330f729Sjoerg });
2307330f729Sjoerg }
2317330f729Sjoerg
2327330f729Sjoerg //===----------------------------------------------------------------------===//
2337330f729Sjoerg // Methods for easy access to the global variables in the module.
2347330f729Sjoerg //
2357330f729Sjoerg
2367330f729Sjoerg // getNamedAlias - Look up the specified global in the module symbol table.
2377330f729Sjoerg // If it does not exist, return null.
2387330f729Sjoerg //
getNamedAlias(StringRef Name) const2397330f729Sjoerg GlobalAlias *Module::getNamedAlias(StringRef Name) const {
2407330f729Sjoerg return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
2417330f729Sjoerg }
2427330f729Sjoerg
getNamedIFunc(StringRef Name) const2437330f729Sjoerg GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
2447330f729Sjoerg return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
2457330f729Sjoerg }
2467330f729Sjoerg
2477330f729Sjoerg /// getNamedMetadata - Return the first NamedMDNode in the module with the
2487330f729Sjoerg /// specified name. This method returns null if a NamedMDNode with the
2497330f729Sjoerg /// specified name is not found.
getNamedMetadata(const Twine & Name) const2507330f729Sjoerg NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
2517330f729Sjoerg SmallString<256> NameData;
2527330f729Sjoerg StringRef NameRef = Name.toStringRef(NameData);
253*82d56013Sjoerg return NamedMDSymTab.lookup(NameRef);
2547330f729Sjoerg }
2557330f729Sjoerg
2567330f729Sjoerg /// getOrInsertNamedMetadata - Return the first named MDNode in the module
2577330f729Sjoerg /// with the specified name. This method returns a new NamedMDNode if a
2587330f729Sjoerg /// NamedMDNode with the specified name is not found.
getOrInsertNamedMetadata(StringRef Name)2597330f729Sjoerg NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
260*82d56013Sjoerg NamedMDNode *&NMD = NamedMDSymTab[Name];
2617330f729Sjoerg if (!NMD) {
2627330f729Sjoerg NMD = new NamedMDNode(Name);
2637330f729Sjoerg NMD->setParent(this);
2647330f729Sjoerg NamedMDList.push_back(NMD);
2657330f729Sjoerg }
2667330f729Sjoerg return NMD;
2677330f729Sjoerg }
2687330f729Sjoerg
2697330f729Sjoerg /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
2707330f729Sjoerg /// delete it.
eraseNamedMetadata(NamedMDNode * NMD)2717330f729Sjoerg void Module::eraseNamedMetadata(NamedMDNode *NMD) {
272*82d56013Sjoerg NamedMDSymTab.erase(NMD->getName());
2737330f729Sjoerg NamedMDList.erase(NMD->getIterator());
2747330f729Sjoerg }
2757330f729Sjoerg
isValidModFlagBehavior(Metadata * MD,ModFlagBehavior & MFB)2767330f729Sjoerg bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
2777330f729Sjoerg if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
2787330f729Sjoerg uint64_t Val = Behavior->getLimitedValue();
2797330f729Sjoerg if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
2807330f729Sjoerg MFB = static_cast<ModFlagBehavior>(Val);
2817330f729Sjoerg return true;
2827330f729Sjoerg }
2837330f729Sjoerg }
2847330f729Sjoerg return false;
2857330f729Sjoerg }
2867330f729Sjoerg
isValidModuleFlag(const MDNode & ModFlag,ModFlagBehavior & MFB,MDString * & Key,Metadata * & Val)287*82d56013Sjoerg bool Module::isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB,
288*82d56013Sjoerg MDString *&Key, Metadata *&Val) {
289*82d56013Sjoerg if (ModFlag.getNumOperands() < 3)
290*82d56013Sjoerg return false;
291*82d56013Sjoerg if (!isValidModFlagBehavior(ModFlag.getOperand(0), MFB))
292*82d56013Sjoerg return false;
293*82d56013Sjoerg MDString *K = dyn_cast_or_null<MDString>(ModFlag.getOperand(1));
294*82d56013Sjoerg if (!K)
295*82d56013Sjoerg return false;
296*82d56013Sjoerg Key = K;
297*82d56013Sjoerg Val = ModFlag.getOperand(2);
298*82d56013Sjoerg return true;
299*82d56013Sjoerg }
300*82d56013Sjoerg
3017330f729Sjoerg /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
3027330f729Sjoerg void Module::
getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> & Flags) const3037330f729Sjoerg getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
3047330f729Sjoerg const NamedMDNode *ModFlags = getModuleFlagsMetadata();
3057330f729Sjoerg if (!ModFlags) return;
3067330f729Sjoerg
3077330f729Sjoerg for (const MDNode *Flag : ModFlags->operands()) {
3087330f729Sjoerg ModFlagBehavior MFB;
309*82d56013Sjoerg MDString *Key = nullptr;
310*82d56013Sjoerg Metadata *Val = nullptr;
311*82d56013Sjoerg if (isValidModuleFlag(*Flag, MFB, Key, Val)) {
3127330f729Sjoerg // Check the operands of the MDNode before accessing the operands.
3137330f729Sjoerg // The verifier will actually catch these failures.
3147330f729Sjoerg Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
3157330f729Sjoerg }
3167330f729Sjoerg }
3177330f729Sjoerg }
3187330f729Sjoerg
3197330f729Sjoerg /// Return the corresponding value if Key appears in module flags, otherwise
3207330f729Sjoerg /// return null.
getModuleFlag(StringRef Key) const3217330f729Sjoerg Metadata *Module::getModuleFlag(StringRef Key) const {
3227330f729Sjoerg SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
3237330f729Sjoerg getModuleFlagsMetadata(ModuleFlags);
3247330f729Sjoerg for (const ModuleFlagEntry &MFE : ModuleFlags) {
3257330f729Sjoerg if (Key == MFE.Key->getString())
3267330f729Sjoerg return MFE.Val;
3277330f729Sjoerg }
3287330f729Sjoerg return nullptr;
3297330f729Sjoerg }
3307330f729Sjoerg
3317330f729Sjoerg /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
3327330f729Sjoerg /// represents module-level flags. This method returns null if there are no
3337330f729Sjoerg /// module-level flags.
getModuleFlagsMetadata() const3347330f729Sjoerg NamedMDNode *Module::getModuleFlagsMetadata() const {
3357330f729Sjoerg return getNamedMetadata("llvm.module.flags");
3367330f729Sjoerg }
3377330f729Sjoerg
3387330f729Sjoerg /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
3397330f729Sjoerg /// represents module-level flags. If module-level flags aren't found, it
3407330f729Sjoerg /// creates the named metadata that contains them.
getOrInsertModuleFlagsMetadata()3417330f729Sjoerg NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
3427330f729Sjoerg return getOrInsertNamedMetadata("llvm.module.flags");
3437330f729Sjoerg }
3447330f729Sjoerg
3457330f729Sjoerg /// addModuleFlag - Add a module-level flag to the module-level flags
3467330f729Sjoerg /// metadata. It will create the module-level flags named metadata if it doesn't
3477330f729Sjoerg /// already exist.
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,Metadata * Val)3487330f729Sjoerg void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
3497330f729Sjoerg Metadata *Val) {
3507330f729Sjoerg Type *Int32Ty = Type::getInt32Ty(Context);
3517330f729Sjoerg Metadata *Ops[3] = {
3527330f729Sjoerg ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
3537330f729Sjoerg MDString::get(Context, Key), Val};
3547330f729Sjoerg getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
3557330f729Sjoerg }
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,Constant * Val)3567330f729Sjoerg void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
3577330f729Sjoerg Constant *Val) {
3587330f729Sjoerg addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
3597330f729Sjoerg }
addModuleFlag(ModFlagBehavior Behavior,StringRef Key,uint32_t Val)3607330f729Sjoerg void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
3617330f729Sjoerg uint32_t Val) {
3627330f729Sjoerg Type *Int32Ty = Type::getInt32Ty(Context);
3637330f729Sjoerg addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
3647330f729Sjoerg }
addModuleFlag(MDNode * Node)3657330f729Sjoerg void Module::addModuleFlag(MDNode *Node) {
3667330f729Sjoerg assert(Node->getNumOperands() == 3 &&
3677330f729Sjoerg "Invalid number of operands for module flag!");
3687330f729Sjoerg assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
3697330f729Sjoerg isa<MDString>(Node->getOperand(1)) &&
3707330f729Sjoerg "Invalid operand types for module flag!");
3717330f729Sjoerg getOrInsertModuleFlagsMetadata()->addOperand(Node);
3727330f729Sjoerg }
3737330f729Sjoerg
setModuleFlag(ModFlagBehavior Behavior,StringRef Key,Metadata * Val)374*82d56013Sjoerg void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
375*82d56013Sjoerg Metadata *Val) {
376*82d56013Sjoerg NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
377*82d56013Sjoerg // Replace the flag if it already exists.
378*82d56013Sjoerg for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
379*82d56013Sjoerg MDNode *Flag = ModFlags->getOperand(I);
380*82d56013Sjoerg ModFlagBehavior MFB;
381*82d56013Sjoerg MDString *K = nullptr;
382*82d56013Sjoerg Metadata *V = nullptr;
383*82d56013Sjoerg if (isValidModuleFlag(*Flag, MFB, K, V) && K->getString() == Key) {
384*82d56013Sjoerg Flag->replaceOperandWith(2, Val);
385*82d56013Sjoerg return;
386*82d56013Sjoerg }
387*82d56013Sjoerg }
388*82d56013Sjoerg addModuleFlag(Behavior, Key, Val);
389*82d56013Sjoerg }
390*82d56013Sjoerg
setDataLayout(StringRef Desc)3917330f729Sjoerg void Module::setDataLayout(StringRef Desc) {
3927330f729Sjoerg DL.reset(Desc);
3937330f729Sjoerg }
3947330f729Sjoerg
setDataLayout(const DataLayout & Other)3957330f729Sjoerg void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
3967330f729Sjoerg
getDataLayout() const3977330f729Sjoerg const DataLayout &Module::getDataLayout() const { return DL; }
3987330f729Sjoerg
operator *() const3997330f729Sjoerg DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
4007330f729Sjoerg return cast<DICompileUnit>(CUs->getOperand(Idx));
4017330f729Sjoerg }
operator ->() const4027330f729Sjoerg DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
4037330f729Sjoerg return cast<DICompileUnit>(CUs->getOperand(Idx));
4047330f729Sjoerg }
4057330f729Sjoerg
SkipNoDebugCUs()4067330f729Sjoerg void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
4077330f729Sjoerg while (CUs && (Idx < CUs->getNumOperands()) &&
4087330f729Sjoerg ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
4097330f729Sjoerg ++Idx;
4107330f729Sjoerg }
4117330f729Sjoerg
global_objects()412*82d56013Sjoerg iterator_range<Module::global_object_iterator> Module::global_objects() {
413*82d56013Sjoerg return concat<GlobalObject>(functions(), globals());
414*82d56013Sjoerg }
415*82d56013Sjoerg iterator_range<Module::const_global_object_iterator>
global_objects() const416*82d56013Sjoerg Module::global_objects() const {
417*82d56013Sjoerg return concat<const GlobalObject>(functions(), globals());
418*82d56013Sjoerg }
419*82d56013Sjoerg
global_values()420*82d56013Sjoerg iterator_range<Module::global_value_iterator> Module::global_values() {
421*82d56013Sjoerg return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
422*82d56013Sjoerg }
423*82d56013Sjoerg iterator_range<Module::const_global_value_iterator>
global_values() const424*82d56013Sjoerg Module::global_values() const {
425*82d56013Sjoerg return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
426*82d56013Sjoerg }
427*82d56013Sjoerg
4287330f729Sjoerg //===----------------------------------------------------------------------===//
4297330f729Sjoerg // Methods to control the materialization of GlobalValues in the Module.
4307330f729Sjoerg //
setMaterializer(GVMaterializer * GVM)4317330f729Sjoerg void Module::setMaterializer(GVMaterializer *GVM) {
4327330f729Sjoerg assert(!Materializer &&
4337330f729Sjoerg "Module already has a GVMaterializer. Call materializeAll"
4347330f729Sjoerg " to clear it out before setting another one.");
4357330f729Sjoerg Materializer.reset(GVM);
4367330f729Sjoerg }
4377330f729Sjoerg
materialize(GlobalValue * GV)4387330f729Sjoerg Error Module::materialize(GlobalValue *GV) {
4397330f729Sjoerg if (!Materializer)
4407330f729Sjoerg return Error::success();
4417330f729Sjoerg
4427330f729Sjoerg return Materializer->materialize(GV);
4437330f729Sjoerg }
4447330f729Sjoerg
materializeAll()4457330f729Sjoerg Error Module::materializeAll() {
4467330f729Sjoerg if (!Materializer)
4477330f729Sjoerg return Error::success();
4487330f729Sjoerg std::unique_ptr<GVMaterializer> M = std::move(Materializer);
4497330f729Sjoerg return M->materializeModule();
4507330f729Sjoerg }
4517330f729Sjoerg
materializeMetadata()4527330f729Sjoerg Error Module::materializeMetadata() {
4537330f729Sjoerg if (!Materializer)
4547330f729Sjoerg return Error::success();
4557330f729Sjoerg return Materializer->materializeMetadata();
4567330f729Sjoerg }
4577330f729Sjoerg
4587330f729Sjoerg //===----------------------------------------------------------------------===//
4597330f729Sjoerg // Other module related stuff.
4607330f729Sjoerg //
4617330f729Sjoerg
getIdentifiedStructTypes() const4627330f729Sjoerg std::vector<StructType *> Module::getIdentifiedStructTypes() const {
4637330f729Sjoerg // If we have a materializer, it is possible that some unread function
4647330f729Sjoerg // uses a type that is currently not visible to a TypeFinder, so ask
4657330f729Sjoerg // the materializer which types it created.
4667330f729Sjoerg if (Materializer)
4677330f729Sjoerg return Materializer->getIdentifiedStructTypes();
4687330f729Sjoerg
4697330f729Sjoerg std::vector<StructType *> Ret;
4707330f729Sjoerg TypeFinder SrcStructTypes;
4717330f729Sjoerg SrcStructTypes.run(*this, true);
4727330f729Sjoerg Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
4737330f729Sjoerg return Ret;
4747330f729Sjoerg }
4757330f729Sjoerg
getUniqueIntrinsicName(StringRef BaseName,Intrinsic::ID Id,const FunctionType * Proto)476*82d56013Sjoerg std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
477*82d56013Sjoerg const FunctionType *Proto) {
478*82d56013Sjoerg auto Encode = [&BaseName](unsigned Suffix) {
479*82d56013Sjoerg return (Twine(BaseName) + "." + Twine(Suffix)).str();
480*82d56013Sjoerg };
481*82d56013Sjoerg
482*82d56013Sjoerg {
483*82d56013Sjoerg // fast path - the prototype is already known
484*82d56013Sjoerg auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
485*82d56013Sjoerg if (!UinItInserted.second)
486*82d56013Sjoerg return Encode(UinItInserted.first->second);
487*82d56013Sjoerg }
488*82d56013Sjoerg
489*82d56013Sjoerg // Not known yet. A new entry was created with index 0. Check if there already
490*82d56013Sjoerg // exists a matching declaration, or select a new entry.
491*82d56013Sjoerg
492*82d56013Sjoerg // Start looking for names with the current known maximum count (or 0).
493*82d56013Sjoerg auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
494*82d56013Sjoerg unsigned Count = NiidItInserted.first->second;
495*82d56013Sjoerg
496*82d56013Sjoerg // This might be slow if a whole population of intrinsics already existed, but
497*82d56013Sjoerg // we cache the values for later usage.
498*82d56013Sjoerg std::string NewName;
499*82d56013Sjoerg while (true) {
500*82d56013Sjoerg NewName = Encode(Count);
501*82d56013Sjoerg GlobalValue *F = getNamedValue(NewName);
502*82d56013Sjoerg if (!F) {
503*82d56013Sjoerg // Reserve this entry for the new proto
504*82d56013Sjoerg UniquedIntrinsicNames[{Id, Proto}] = Count;
505*82d56013Sjoerg break;
506*82d56013Sjoerg }
507*82d56013Sjoerg
508*82d56013Sjoerg // A declaration with this name already exists. Remember it.
509*82d56013Sjoerg FunctionType *FT = dyn_cast<FunctionType>(F->getType()->getElementType());
510*82d56013Sjoerg auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
511*82d56013Sjoerg if (FT == Proto) {
512*82d56013Sjoerg // It was a declaration for our prototype. This entry was allocated in the
513*82d56013Sjoerg // beginning. Update the count to match the existing declaration.
514*82d56013Sjoerg UinItInserted.first->second = Count;
515*82d56013Sjoerg break;
516*82d56013Sjoerg }
517*82d56013Sjoerg
518*82d56013Sjoerg ++Count;
519*82d56013Sjoerg }
520*82d56013Sjoerg
521*82d56013Sjoerg NiidItInserted.first->second = Count + 1;
522*82d56013Sjoerg
523*82d56013Sjoerg return NewName;
524*82d56013Sjoerg }
525*82d56013Sjoerg
5267330f729Sjoerg // dropAllReferences() - This function causes all the subelements to "let go"
5277330f729Sjoerg // of all references that they are maintaining. This allows one to 'delete' a
5287330f729Sjoerg // whole module at a time, even though there may be circular references... first
5297330f729Sjoerg // all references are dropped, and all use counts go to zero. Then everything
5307330f729Sjoerg // is deleted for real. Note that no operations are valid on an object that
5317330f729Sjoerg // has "dropped all references", except operator delete.
5327330f729Sjoerg //
dropAllReferences()5337330f729Sjoerg void Module::dropAllReferences() {
5347330f729Sjoerg for (Function &F : *this)
5357330f729Sjoerg F.dropAllReferences();
5367330f729Sjoerg
5377330f729Sjoerg for (GlobalVariable &GV : globals())
5387330f729Sjoerg GV.dropAllReferences();
5397330f729Sjoerg
5407330f729Sjoerg for (GlobalAlias &GA : aliases())
5417330f729Sjoerg GA.dropAllReferences();
5427330f729Sjoerg
5437330f729Sjoerg for (GlobalIFunc &GIF : ifuncs())
5447330f729Sjoerg GIF.dropAllReferences();
5457330f729Sjoerg }
5467330f729Sjoerg
getNumberRegisterParameters() const5477330f729Sjoerg unsigned Module::getNumberRegisterParameters() const {
5487330f729Sjoerg auto *Val =
5497330f729Sjoerg cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
5507330f729Sjoerg if (!Val)
5517330f729Sjoerg return 0;
5527330f729Sjoerg return cast<ConstantInt>(Val->getValue())->getZExtValue();
5537330f729Sjoerg }
5547330f729Sjoerg
getDwarfVersion() const5557330f729Sjoerg unsigned Module::getDwarfVersion() const {
5567330f729Sjoerg auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
5577330f729Sjoerg if (!Val)
5587330f729Sjoerg return 0;
5597330f729Sjoerg return cast<ConstantInt>(Val->getValue())->getZExtValue();
5607330f729Sjoerg }
5617330f729Sjoerg
isDwarf64() const562*82d56013Sjoerg bool Module::isDwarf64() const {
563*82d56013Sjoerg auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64"));
564*82d56013Sjoerg return Val && cast<ConstantInt>(Val->getValue())->isOne();
565*82d56013Sjoerg }
566*82d56013Sjoerg
getCodeViewFlag() const5677330f729Sjoerg unsigned Module::getCodeViewFlag() const {
5687330f729Sjoerg auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
5697330f729Sjoerg if (!Val)
5707330f729Sjoerg return 0;
5717330f729Sjoerg return cast<ConstantInt>(Val->getValue())->getZExtValue();
5727330f729Sjoerg }
5737330f729Sjoerg
getInstructionCount() const574*82d56013Sjoerg unsigned Module::getInstructionCount() const {
5757330f729Sjoerg unsigned NumInstrs = 0;
576*82d56013Sjoerg for (const Function &F : FunctionList)
5777330f729Sjoerg NumInstrs += F.getInstructionCount();
5787330f729Sjoerg return NumInstrs;
5797330f729Sjoerg }
5807330f729Sjoerg
getOrInsertComdat(StringRef Name)5817330f729Sjoerg Comdat *Module::getOrInsertComdat(StringRef Name) {
5827330f729Sjoerg auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
5837330f729Sjoerg Entry.second.Name = &Entry;
5847330f729Sjoerg return &Entry.second;
5857330f729Sjoerg }
5867330f729Sjoerg
getPICLevel() const5877330f729Sjoerg PICLevel::Level Module::getPICLevel() const {
5887330f729Sjoerg auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
5897330f729Sjoerg
5907330f729Sjoerg if (!Val)
5917330f729Sjoerg return PICLevel::NotPIC;
5927330f729Sjoerg
5937330f729Sjoerg return static_cast<PICLevel::Level>(
5947330f729Sjoerg cast<ConstantInt>(Val->getValue())->getZExtValue());
5957330f729Sjoerg }
5967330f729Sjoerg
setPICLevel(PICLevel::Level PL)5977330f729Sjoerg void Module::setPICLevel(PICLevel::Level PL) {
5987330f729Sjoerg addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
5997330f729Sjoerg }
6007330f729Sjoerg
getPIELevel() const6017330f729Sjoerg PIELevel::Level Module::getPIELevel() const {
6027330f729Sjoerg auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
6037330f729Sjoerg
6047330f729Sjoerg if (!Val)
6057330f729Sjoerg return PIELevel::Default;
6067330f729Sjoerg
6077330f729Sjoerg return static_cast<PIELevel::Level>(
6087330f729Sjoerg cast<ConstantInt>(Val->getValue())->getZExtValue());
6097330f729Sjoerg }
6107330f729Sjoerg
setPIELevel(PIELevel::Level PL)6117330f729Sjoerg void Module::setPIELevel(PIELevel::Level PL) {
6127330f729Sjoerg addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
6137330f729Sjoerg }
6147330f729Sjoerg
getCodeModel() const6157330f729Sjoerg Optional<CodeModel::Model> Module::getCodeModel() const {
6167330f729Sjoerg auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
6177330f729Sjoerg
6187330f729Sjoerg if (!Val)
6197330f729Sjoerg return None;
6207330f729Sjoerg
6217330f729Sjoerg return static_cast<CodeModel::Model>(
6227330f729Sjoerg cast<ConstantInt>(Val->getValue())->getZExtValue());
6237330f729Sjoerg }
6247330f729Sjoerg
setCodeModel(CodeModel::Model CL)6257330f729Sjoerg void Module::setCodeModel(CodeModel::Model CL) {
6267330f729Sjoerg // Linking object files with different code models is undefined behavior
6277330f729Sjoerg // because the compiler would have to generate additional code (to span
6287330f729Sjoerg // longer jumps) if a larger code model is used with a smaller one.
6297330f729Sjoerg // Therefore we will treat attempts to mix code models as an error.
6307330f729Sjoerg addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
6317330f729Sjoerg }
6327330f729Sjoerg
setProfileSummary(Metadata * M,ProfileSummary::Kind Kind)6337330f729Sjoerg void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
6347330f729Sjoerg if (Kind == ProfileSummary::PSK_CSInstr)
635*82d56013Sjoerg setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
6367330f729Sjoerg else
637*82d56013Sjoerg setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
6387330f729Sjoerg }
6397330f729Sjoerg
getProfileSummary(bool IsCS) const640*82d56013Sjoerg Metadata *Module::getProfileSummary(bool IsCS) const {
6417330f729Sjoerg return (IsCS ? getModuleFlag("CSProfileSummary")
6427330f729Sjoerg : getModuleFlag("ProfileSummary"));
6437330f729Sjoerg }
6447330f729Sjoerg
getSemanticInterposition() const645*82d56013Sjoerg bool Module::getSemanticInterposition() const {
646*82d56013Sjoerg Metadata *MF = getModuleFlag("SemanticInterposition");
647*82d56013Sjoerg
648*82d56013Sjoerg auto *Val = cast_or_null<ConstantAsMetadata>(MF);
649*82d56013Sjoerg if (!Val)
650*82d56013Sjoerg return false;
651*82d56013Sjoerg
652*82d56013Sjoerg return cast<ConstantInt>(Val->getValue())->getZExtValue();
653*82d56013Sjoerg }
654*82d56013Sjoerg
setSemanticInterposition(bool SI)655*82d56013Sjoerg void Module::setSemanticInterposition(bool SI) {
656*82d56013Sjoerg addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI);
657*82d56013Sjoerg }
658*82d56013Sjoerg
setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB)6597330f729Sjoerg void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
6607330f729Sjoerg OwnedMemoryBuffer = std::move(MB);
6617330f729Sjoerg }
6627330f729Sjoerg
getRtLibUseGOT() const6637330f729Sjoerg bool Module::getRtLibUseGOT() const {
6647330f729Sjoerg auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
6657330f729Sjoerg return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
6667330f729Sjoerg }
6677330f729Sjoerg
setRtLibUseGOT()6687330f729Sjoerg void Module::setRtLibUseGOT() {
6697330f729Sjoerg addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
6707330f729Sjoerg }
6717330f729Sjoerg
getUwtable() const672*82d56013Sjoerg bool Module::getUwtable() const {
673*82d56013Sjoerg auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable"));
674*82d56013Sjoerg return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
675*82d56013Sjoerg }
676*82d56013Sjoerg
setUwtable()677*82d56013Sjoerg void Module::setUwtable() { addModuleFlag(ModFlagBehavior::Max, "uwtable", 1); }
678*82d56013Sjoerg
getFramePointer() const679*82d56013Sjoerg FramePointerKind Module::getFramePointer() const {
680*82d56013Sjoerg auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer"));
681*82d56013Sjoerg return static_cast<FramePointerKind>(
682*82d56013Sjoerg Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
683*82d56013Sjoerg }
684*82d56013Sjoerg
setFramePointer(FramePointerKind Kind)685*82d56013Sjoerg void Module::setFramePointer(FramePointerKind Kind) {
686*82d56013Sjoerg addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind));
687*82d56013Sjoerg }
688*82d56013Sjoerg
getStackProtectorGuard() const689*82d56013Sjoerg StringRef Module::getStackProtectorGuard() const {
690*82d56013Sjoerg Metadata *MD = getModuleFlag("stack-protector-guard");
691*82d56013Sjoerg if (auto *MDS = dyn_cast_or_null<MDString>(MD))
692*82d56013Sjoerg return MDS->getString();
693*82d56013Sjoerg return {};
694*82d56013Sjoerg }
695*82d56013Sjoerg
setStackProtectorGuard(StringRef Kind)696*82d56013Sjoerg void Module::setStackProtectorGuard(StringRef Kind) {
697*82d56013Sjoerg MDString *ID = MDString::get(getContext(), Kind);
698*82d56013Sjoerg addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID);
699*82d56013Sjoerg }
700*82d56013Sjoerg
getStackProtectorGuardReg() const701*82d56013Sjoerg StringRef Module::getStackProtectorGuardReg() const {
702*82d56013Sjoerg Metadata *MD = getModuleFlag("stack-protector-guard-reg");
703*82d56013Sjoerg if (auto *MDS = dyn_cast_or_null<MDString>(MD))
704*82d56013Sjoerg return MDS->getString();
705*82d56013Sjoerg return {};
706*82d56013Sjoerg }
707*82d56013Sjoerg
setStackProtectorGuardReg(StringRef Reg)708*82d56013Sjoerg void Module::setStackProtectorGuardReg(StringRef Reg) {
709*82d56013Sjoerg MDString *ID = MDString::get(getContext(), Reg);
710*82d56013Sjoerg addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID);
711*82d56013Sjoerg }
712*82d56013Sjoerg
getStackProtectorGuardOffset() const713*82d56013Sjoerg int Module::getStackProtectorGuardOffset() const {
714*82d56013Sjoerg Metadata *MD = getModuleFlag("stack-protector-guard-offset");
715*82d56013Sjoerg if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
716*82d56013Sjoerg return CI->getSExtValue();
717*82d56013Sjoerg return INT_MAX;
718*82d56013Sjoerg }
719*82d56013Sjoerg
setStackProtectorGuardOffset(int Offset)720*82d56013Sjoerg void Module::setStackProtectorGuardOffset(int Offset) {
721*82d56013Sjoerg addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset);
722*82d56013Sjoerg }
723*82d56013Sjoerg
setSDKVersion(const VersionTuple & V)7247330f729Sjoerg void Module::setSDKVersion(const VersionTuple &V) {
7257330f729Sjoerg SmallVector<unsigned, 3> Entries;
7267330f729Sjoerg Entries.push_back(V.getMajor());
7277330f729Sjoerg if (auto Minor = V.getMinor()) {
7287330f729Sjoerg Entries.push_back(*Minor);
7297330f729Sjoerg if (auto Subminor = V.getSubminor())
7307330f729Sjoerg Entries.push_back(*Subminor);
7317330f729Sjoerg // Ignore the 'build' component as it can't be represented in the object
7327330f729Sjoerg // file.
7337330f729Sjoerg }
7347330f729Sjoerg addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
7357330f729Sjoerg ConstantDataArray::get(Context, Entries));
7367330f729Sjoerg }
7377330f729Sjoerg
getSDKVersion() const7387330f729Sjoerg VersionTuple Module::getSDKVersion() const {
7397330f729Sjoerg auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
7407330f729Sjoerg if (!CM)
7417330f729Sjoerg return {};
7427330f729Sjoerg auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
7437330f729Sjoerg if (!Arr)
7447330f729Sjoerg return {};
7457330f729Sjoerg auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
7467330f729Sjoerg if (Index >= Arr->getNumElements())
7477330f729Sjoerg return None;
7487330f729Sjoerg return (unsigned)Arr->getElementAsInteger(Index);
7497330f729Sjoerg };
7507330f729Sjoerg auto Major = getVersionComponent(0);
7517330f729Sjoerg if (!Major)
7527330f729Sjoerg return {};
7537330f729Sjoerg VersionTuple Result = VersionTuple(*Major);
7547330f729Sjoerg if (auto Minor = getVersionComponent(1)) {
7557330f729Sjoerg Result = VersionTuple(*Major, *Minor);
7567330f729Sjoerg if (auto Subminor = getVersionComponent(2)) {
7577330f729Sjoerg Result = VersionTuple(*Major, *Minor, *Subminor);
7587330f729Sjoerg }
7597330f729Sjoerg }
7607330f729Sjoerg return Result;
7617330f729Sjoerg }
7627330f729Sjoerg
collectUsedGlobalVariables(const Module & M,SmallVectorImpl<GlobalValue * > & Vec,bool CompilerUsed)7637330f729Sjoerg GlobalVariable *llvm::collectUsedGlobalVariables(
764*82d56013Sjoerg const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
7657330f729Sjoerg const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
7667330f729Sjoerg GlobalVariable *GV = M.getGlobalVariable(Name);
7677330f729Sjoerg if (!GV || !GV->hasInitializer())
7687330f729Sjoerg return GV;
7697330f729Sjoerg
7707330f729Sjoerg const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
7717330f729Sjoerg for (Value *Op : Init->operands()) {
7727330f729Sjoerg GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
773*82d56013Sjoerg Vec.push_back(G);
7747330f729Sjoerg }
7757330f729Sjoerg return GV;
7767330f729Sjoerg }
777*82d56013Sjoerg
setPartialSampleProfileRatio(const ModuleSummaryIndex & Index)778*82d56013Sjoerg void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) {
779*82d56013Sjoerg if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
780*82d56013Sjoerg std::unique_ptr<ProfileSummary> ProfileSummary(
781*82d56013Sjoerg ProfileSummary::getFromMD(SummaryMD));
782*82d56013Sjoerg if (ProfileSummary) {
783*82d56013Sjoerg if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample ||
784*82d56013Sjoerg !ProfileSummary->isPartialProfile())
785*82d56013Sjoerg return;
786*82d56013Sjoerg uint64_t BlockCount = Index.getBlockCount();
787*82d56013Sjoerg uint32_t NumCounts = ProfileSummary->getNumCounts();
788*82d56013Sjoerg if (!NumCounts)
789*82d56013Sjoerg return;
790*82d56013Sjoerg double Ratio = (double)BlockCount / NumCounts;
791*82d56013Sjoerg ProfileSummary->setPartialProfileRatio(Ratio);
792*82d56013Sjoerg setProfileSummary(ProfileSummary->getMD(getContext()),
793*82d56013Sjoerg ProfileSummary::PSK_Sample);
794*82d56013Sjoerg }
795*82d56013Sjoerg }
796*82d56013Sjoerg }
797