1eba7e4ecSEugene Zelenko //===- Module.cpp - Implement the Module class ----------------------------===// 2ef860a24SChandler Carruth // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6ef860a24SChandler Carruth // 7ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 8ef860a24SChandler Carruth // 9ef860a24SChandler Carruth // This file implements the Module class for the IR library. 10ef860a24SChandler Carruth // 11ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 12ef860a24SChandler Carruth 136bda14b3SChandler Carruth #include "llvm/IR/Module.h" 14ef860a24SChandler Carruth #include "SymbolTableListTraitsImpl.h" 153dea3f9eSCaroline Tice #include "llvm/ADT/Optional.h" 16ef860a24SChandler Carruth #include "llvm/ADT/SmallString.h" 17eba7e4ecSEugene Zelenko #include "llvm/ADT/SmallVector.h" 18eba7e4ecSEugene Zelenko #include "llvm/ADT/StringMap.h" 19eba7e4ecSEugene Zelenko #include "llvm/ADT/StringRef.h" 20eba7e4ecSEugene Zelenko #include "llvm/ADT/Twine.h" 21eba7e4ecSEugene Zelenko #include "llvm/IR/Attributes.h" 22eba7e4ecSEugene Zelenko #include "llvm/IR/Comdat.h" 239fb823bbSChandler Carruth #include "llvm/IR/Constants.h" 24eba7e4ecSEugene Zelenko #include "llvm/IR/DataLayout.h" 255992a72bSAdrian Prantl #include "llvm/IR/DebugInfoMetadata.h" 266bda14b3SChandler Carruth #include "llvm/IR/DerivedTypes.h" 27eba7e4ecSEugene Zelenko #include "llvm/IR/Function.h" 286bda14b3SChandler Carruth #include "llvm/IR/GVMaterializer.h" 29eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalAlias.h" 30eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalIFunc.h" 31eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalValue.h" 32eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalVariable.h" 339fb823bbSChandler Carruth #include "llvm/IR/LLVMContext.h" 34eba7e4ecSEugene Zelenko #include "llvm/IR/Metadata.h" 356c27c61dSHiroshi Yamauchi #include "llvm/IR/ModuleSummaryIndex.h" 36eba7e4ecSEugene Zelenko #include "llvm/IR/SymbolTableListTraits.h" 37eba7e4ecSEugene Zelenko #include "llvm/IR/Type.h" 382fa1e43aSRafael Espindola #include "llvm/IR/TypeFinder.h" 39eba7e4ecSEugene Zelenko #include "llvm/IR/Value.h" 40eba7e4ecSEugene Zelenko #include "llvm/IR/ValueSymbolTable.h" 41eba7e4ecSEugene Zelenko #include "llvm/Support/Casting.h" 42eba7e4ecSEugene Zelenko #include "llvm/Support/CodeGen.h" 437f00d0a1SPeter Collingbourne #include "llvm/Support/Error.h" 44e2dcf7c3SPeter Collingbourne #include "llvm/Support/MemoryBuffer.h" 45144829d3SJF Bastien #include "llvm/Support/Path.h" 46144829d3SJF Bastien #include "llvm/Support/RandomNumberGenerator.h" 47afa75d78SAlex Lorenz #include "llvm/Support/VersionTuple.h" 48ef860a24SChandler Carruth #include <algorithm> 49eba7e4ecSEugene Zelenko #include <cassert> 50eba7e4ecSEugene Zelenko #include <cstdint> 51eba7e4ecSEugene Zelenko #include <memory> 52eba7e4ecSEugene Zelenko #include <utility> 53eba7e4ecSEugene Zelenko #include <vector> 54083ca9bbSHans Wennborg 55ef860a24SChandler Carruth using namespace llvm; 56ef860a24SChandler Carruth 57ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 58ef860a24SChandler Carruth // Methods to implement the globals and functions lists. 59ef860a24SChandler Carruth // 60ef860a24SChandler Carruth 61ef860a24SChandler Carruth // Explicit instantiations of SymbolTableListTraits since some of the methods 62ef860a24SChandler Carruth // are not in the public header file. 6337bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<Function>; 6437bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<GlobalVariable>; 6537bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<GlobalAlias>; 66a1feff70SDmitry Polukhin template class llvm::SymbolTableListTraits<GlobalIFunc>; 67ef860a24SChandler Carruth 68ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 69ef860a24SChandler Carruth // Primitive Module methods. 70ef860a24SChandler Carruth // 71ef860a24SChandler Carruth 72ef860a24SChandler Carruth Module::Module(StringRef MID, LLVMContext &C) 738d257627SHasyimi Bahrudin : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>(-1)), 74*2bc684cbSKazu Hirata ModuleID(std::string(MID)), SourceFileName(std::string(MID)), DL("") { 75ef860a24SChandler Carruth Context.addModule(this); 76ef860a24SChandler Carruth } 77ef860a24SChandler Carruth 78ef860a24SChandler Carruth Module::~Module() { 79ef860a24SChandler Carruth Context.removeModule(this); 80ef860a24SChandler Carruth dropAllReferences(); 81ef860a24SChandler Carruth GlobalList.clear(); 82ef860a24SChandler Carruth FunctionList.clear(); 83ef860a24SChandler Carruth AliasList.clear(); 84a1feff70SDmitry Polukhin IFuncList.clear(); 85ef860a24SChandler Carruth } 86ef860a24SChandler Carruth 8773713f3eSDominic Chen std::unique_ptr<RandomNumberGenerator> 8873713f3eSDominic Chen Module::createRNG(const StringRef Name) const { 8973713f3eSDominic Chen SmallString<32> Salt(Name); 90e6acbdc4SJF Bastien 91e6acbdc4SJF Bastien // This RNG is guaranteed to produce the same random stream only 92e6acbdc4SJF Bastien // when the Module ID and thus the input filename is the same. This 93e6acbdc4SJF Bastien // might be problematic if the input filename extension changes 94e6acbdc4SJF Bastien // (e.g. from .c to .bc or .ll). 95e6acbdc4SJF Bastien // 96e6acbdc4SJF Bastien // We could store this salt in NamedMetadata, but this would make 97e6acbdc4SJF Bastien // the parameter non-const. This would unfortunately make this 98e6acbdc4SJF Bastien // interface unusable by any Machine passes, since they only have a 99e6acbdc4SJF Bastien // const reference to their IR Module. Alternatively we can always 100e6acbdc4SJF Bastien // store salt metadata from the Module constructor. 101e6acbdc4SJF Bastien Salt += sys::path::filename(getModuleIdentifier()); 102e6acbdc4SJF Bastien 10373713f3eSDominic Chen return std::unique_ptr<RandomNumberGenerator>( 10473713f3eSDominic Chen new RandomNumberGenerator(Salt)); 105e6acbdc4SJF Bastien } 106e6acbdc4SJF Bastien 107ef860a24SChandler Carruth /// getNamedValue - Return the first global value in the module with 108ef860a24SChandler Carruth /// the specified name, of arbitrary type. This method returns null 109ef860a24SChandler Carruth /// if a global with the specified name is not found. 110ef860a24SChandler Carruth GlobalValue *Module::getNamedValue(StringRef Name) const { 111ef860a24SChandler Carruth return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name)); 112ef860a24SChandler Carruth } 113ef860a24SChandler Carruth 11403b8c69dSJeroen Dobbelaere unsigned Module::getNumNamedValues() const { 11503b8c69dSJeroen Dobbelaere return getValueSymbolTable().size(); 11603b8c69dSJeroen Dobbelaere } 11703b8c69dSJeroen Dobbelaere 118ef860a24SChandler Carruth /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 119ef860a24SChandler Carruth /// This ID is uniqued across modules in the current LLVMContext. 120ef860a24SChandler Carruth unsigned Module::getMDKindID(StringRef Name) const { 121ef860a24SChandler Carruth return Context.getMDKindID(Name); 122ef860a24SChandler Carruth } 123ef860a24SChandler Carruth 124ef860a24SChandler Carruth /// getMDKindNames - Populate client supplied SmallVector with the name for 125ef860a24SChandler Carruth /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 126ef860a24SChandler Carruth /// so it is filled in as an empty string. 127ef860a24SChandler Carruth void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 128ef860a24SChandler Carruth return Context.getMDKindNames(Result); 129ef860a24SChandler Carruth } 130ef860a24SChandler Carruth 1319303c246SSanjoy Das void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const { 1329303c246SSanjoy Das return Context.getOperandBundleTags(Result); 1339303c246SSanjoy Das } 134ef860a24SChandler Carruth 135ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 136ef860a24SChandler Carruth // Methods for easy access to the functions in the module. 137ef860a24SChandler Carruth // 138ef860a24SChandler Carruth 139ef860a24SChandler Carruth // getOrInsertFunction - Look up the specified function in the module symbol 140ef860a24SChandler Carruth // table. If it does not exist, add a prototype for the function and return 141ef860a24SChandler Carruth // it. This is nice because it allows most passes to get away with not handling 142ef860a24SChandler Carruth // the symbol table directly for this common task. 143ef860a24SChandler Carruth // 14413680223SJames Y Knight FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty, 145b518054bSReid Kleckner AttributeList AttributeList) { 146ef860a24SChandler Carruth // See if we have a definition for the specified function already. 147ef860a24SChandler Carruth GlobalValue *F = getNamedValue(Name); 148c620761cSCraig Topper if (!F) { 149ef860a24SChandler Carruth // Nope, add it 1506bcf2ba2SAlexander Richardson Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, 1516bcf2ba2SAlexander Richardson DL.getProgramAddressSpace(), Name); 152ef860a24SChandler Carruth if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 153ef860a24SChandler Carruth New->setAttributes(AttributeList); 154ef860a24SChandler Carruth FunctionList.push_back(New); 15513680223SJames Y Knight return {Ty, New}; // Return the new prototype. 156ef860a24SChandler Carruth } 157ef860a24SChandler Carruth 158ef860a24SChandler Carruth // If the function exists but has the wrong type, return a bitcast to the 159ef860a24SChandler Carruth // right type. 1606bcf2ba2SAlexander Richardson auto *PTy = PointerType::get(Ty, F->getAddressSpace()); 1616bcf2ba2SAlexander Richardson if (F->getType() != PTy) 16213680223SJames Y Knight return {Ty, ConstantExpr::getBitCast(F, PTy)}; 163ef860a24SChandler Carruth 164ef860a24SChandler Carruth // Otherwise, we just found the existing function or a prototype. 16513680223SJames Y Knight return {Ty, F}; 166ef860a24SChandler Carruth } 167ef860a24SChandler Carruth 16813680223SJames Y Knight FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) { 169b518054bSReid Kleckner return getOrInsertFunction(Name, Ty, AttributeList()); 170ef860a24SChandler Carruth } 171ef860a24SChandler Carruth 172ef860a24SChandler Carruth // getFunction - Look up the specified function in the module symbol table. 173ef860a24SChandler Carruth // If it does not exist, return null. 174ef860a24SChandler Carruth // 175ef860a24SChandler Carruth Function *Module::getFunction(StringRef Name) const { 176ef860a24SChandler Carruth return dyn_cast_or_null<Function>(getNamedValue(Name)); 177ef860a24SChandler Carruth } 178ef860a24SChandler Carruth 179ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 180ef860a24SChandler Carruth // Methods for easy access to the global variables in the module. 181ef860a24SChandler Carruth // 182ef860a24SChandler Carruth 183ef860a24SChandler Carruth /// getGlobalVariable - Look up the specified global variable in the module 184ef860a24SChandler Carruth /// symbol table. If it does not exist, return null. The type argument 185ef860a24SChandler Carruth /// should be the underlying type of the global, i.e., it should not have 186ef860a24SChandler Carruth /// the top-level PointerType, which represents the address of the global. 187ef860a24SChandler Carruth /// If AllowLocal is set to true, this function will return types that 188ef860a24SChandler Carruth /// have an local. By default, these types are not returned. 189ef860a24SChandler Carruth /// 1901dd20e65SCraig Topper GlobalVariable *Module::getGlobalVariable(StringRef Name, 1911dd20e65SCraig Topper bool AllowLocal) const { 192ef860a24SChandler Carruth if (GlobalVariable *Result = 193ef860a24SChandler Carruth dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 194ef860a24SChandler Carruth if (AllowLocal || !Result->hasLocalLinkage()) 195ef860a24SChandler Carruth return Result; 196c620761cSCraig Topper return nullptr; 197ef860a24SChandler Carruth } 198ef860a24SChandler Carruth 199ef860a24SChandler Carruth /// getOrInsertGlobal - Look up the specified global in the module symbol table. 200ef860a24SChandler Carruth /// 1. If it does not exist, add a declaration of the global and return it. 201ef860a24SChandler Carruth /// 2. Else, the global exists but has the wrong type: return the function 202ef860a24SChandler Carruth /// with a constantexpr cast to the right type. 2035200fdf0SMatt Arsenault /// 3. Finally, if the existing global is the correct declaration, return the 204ef860a24SChandler Carruth /// existing global. 2056bc98ad7SPhilip Pfaffe Constant *Module::getOrInsertGlobal( 2066bc98ad7SPhilip Pfaffe StringRef Name, Type *Ty, 2076bc98ad7SPhilip Pfaffe function_ref<GlobalVariable *()> CreateGlobalCallback) { 208ef860a24SChandler Carruth // See if we have a definition for the specified global already. 209ef860a24SChandler Carruth GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)); 2106bc98ad7SPhilip Pfaffe if (!GV) 2116bc98ad7SPhilip Pfaffe GV = CreateGlobalCallback(); 2126bc98ad7SPhilip Pfaffe assert(GV && "The CreateGlobalCallback is expected to create a global"); 213ef860a24SChandler Carruth 214ef860a24SChandler Carruth // If the variable exists but has the wrong type, return a bitcast to the 215ef860a24SChandler Carruth // right type. 21627e783e9SMatt Arsenault Type *GVTy = GV->getType(); 21727e783e9SMatt Arsenault PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace()); 218a90a340fSMatt Arsenault if (GVTy != PTy) 21927e783e9SMatt Arsenault return ConstantExpr::getBitCast(GV, PTy); 220ef860a24SChandler Carruth 221ef860a24SChandler Carruth // Otherwise, we just found the existing function or a prototype. 222ef860a24SChandler Carruth return GV; 223ef860a24SChandler Carruth } 224ef860a24SChandler Carruth 2256bc98ad7SPhilip Pfaffe // Overload to construct a global variable using its constructor's defaults. 2266bc98ad7SPhilip Pfaffe Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 2276bc98ad7SPhilip Pfaffe return getOrInsertGlobal(Name, Ty, [&] { 2286bc98ad7SPhilip Pfaffe return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 2296bc98ad7SPhilip Pfaffe nullptr, Name); 2306bc98ad7SPhilip Pfaffe }); 2316bc98ad7SPhilip Pfaffe } 2326bc98ad7SPhilip Pfaffe 233ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 234ef860a24SChandler Carruth // Methods for easy access to the global variables in the module. 235ef860a24SChandler Carruth // 236ef860a24SChandler Carruth 237ef860a24SChandler Carruth // getNamedAlias - Look up the specified global in the module symbol table. 238ef860a24SChandler Carruth // If it does not exist, return null. 239ef860a24SChandler Carruth // 240ef860a24SChandler Carruth GlobalAlias *Module::getNamedAlias(StringRef Name) const { 241ef860a24SChandler Carruth return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 242ef860a24SChandler Carruth } 243ef860a24SChandler Carruth 244a1feff70SDmitry Polukhin GlobalIFunc *Module::getNamedIFunc(StringRef Name) const { 245a1feff70SDmitry Polukhin return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name)); 246a1feff70SDmitry Polukhin } 247a1feff70SDmitry Polukhin 248ef860a24SChandler Carruth /// getNamedMetadata - Return the first NamedMDNode in the module with the 249ef860a24SChandler Carruth /// specified name. This method returns null if a NamedMDNode with the 250ef860a24SChandler Carruth /// specified name is not found. 251ef860a24SChandler Carruth NamedMDNode *Module::getNamedMetadata(const Twine &Name) const { 252ef860a24SChandler Carruth SmallString<256> NameData; 253ef860a24SChandler Carruth StringRef NameRef = Name.toStringRef(NameData); 254daab9227SBrian Gesiak return NamedMDSymTab.lookup(NameRef); 255ef860a24SChandler Carruth } 256ef860a24SChandler Carruth 257ef860a24SChandler Carruth /// getOrInsertNamedMetadata - Return the first named MDNode in the module 258ef860a24SChandler Carruth /// with the specified name. This method returns a new NamedMDNode if a 259ef860a24SChandler Carruth /// NamedMDNode with the specified name is not found. 260ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 261daab9227SBrian Gesiak NamedMDNode *&NMD = NamedMDSymTab[Name]; 262ef860a24SChandler Carruth if (!NMD) { 263ef860a24SChandler Carruth NMD = new NamedMDNode(Name); 264ef860a24SChandler Carruth NMD->setParent(this); 265ef860a24SChandler Carruth NamedMDList.push_back(NMD); 266ef860a24SChandler Carruth } 267ef860a24SChandler Carruth return NMD; 268ef860a24SChandler Carruth } 269ef860a24SChandler Carruth 270ef860a24SChandler Carruth /// eraseNamedMetadata - Remove the given NamedMDNode from this module and 271ef860a24SChandler Carruth /// delete it. 272ef860a24SChandler Carruth void Module::eraseNamedMetadata(NamedMDNode *NMD) { 273daab9227SBrian Gesiak NamedMDSymTab.erase(NMD->getName()); 27452888a67SDuncan P. N. Exon Smith NamedMDList.erase(NMD->getIterator()); 275ef860a24SChandler Carruth } 276ef860a24SChandler Carruth 2775bf8fef5SDuncan P. N. Exon Smith bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) { 278d7677e7aSDavid Majnemer if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) { 279af023adbSAlexey Samsonov uint64_t Val = Behavior->getLimitedValue(); 280af023adbSAlexey Samsonov if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) { 281af023adbSAlexey Samsonov MFB = static_cast<ModFlagBehavior>(Val); 282af023adbSAlexey Samsonov return true; 283af023adbSAlexey Samsonov } 284af023adbSAlexey Samsonov } 285af023adbSAlexey Samsonov return false; 286af023adbSAlexey Samsonov } 287af023adbSAlexey Samsonov 28801909b4eSHiroshi Yamauchi bool Module::isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB, 28901909b4eSHiroshi Yamauchi MDString *&Key, Metadata *&Val) { 29001909b4eSHiroshi Yamauchi if (ModFlag.getNumOperands() < 3) 29101909b4eSHiroshi Yamauchi return false; 29201909b4eSHiroshi Yamauchi if (!isValidModFlagBehavior(ModFlag.getOperand(0), MFB)) 29301909b4eSHiroshi Yamauchi return false; 29401909b4eSHiroshi Yamauchi MDString *K = dyn_cast_or_null<MDString>(ModFlag.getOperand(1)); 29501909b4eSHiroshi Yamauchi if (!K) 29601909b4eSHiroshi Yamauchi return false; 29701909b4eSHiroshi Yamauchi Key = K; 29801909b4eSHiroshi Yamauchi Val = ModFlag.getOperand(2); 29901909b4eSHiroshi Yamauchi return true; 30001909b4eSHiroshi Yamauchi } 30101909b4eSHiroshi Yamauchi 302ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the module flags in the provided vector. 303ef860a24SChandler Carruth void Module:: 304ef860a24SChandler Carruth getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 305ef860a24SChandler Carruth const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 306ef860a24SChandler Carruth if (!ModFlags) return; 307ef860a24SChandler Carruth 308de36e804SDuncan P. N. Exon Smith for (const MDNode *Flag : ModFlags->operands()) { 309af023adbSAlexey Samsonov ModFlagBehavior MFB; 31001909b4eSHiroshi Yamauchi MDString *Key = nullptr; 31101909b4eSHiroshi Yamauchi Metadata *Val = nullptr; 31201909b4eSHiroshi Yamauchi if (isValidModuleFlag(*Flag, MFB, Key, Val)) { 3138b4306ceSManman Ren // Check the operands of the MDNode before accessing the operands. 3148b4306ceSManman Ren // The verifier will actually catch these failures. 315af023adbSAlexey Samsonov Flags.push_back(ModuleFlagEntry(MFB, Key, Val)); 316ef860a24SChandler Carruth } 317ef860a24SChandler Carruth } 3188b4306ceSManman Ren } 319ef860a24SChandler Carruth 3208bfde891SManman Ren /// Return the corresponding value if Key appears in module flags, otherwise 3218bfde891SManman Ren /// return null. 3225bf8fef5SDuncan P. N. Exon Smith Metadata *Module::getModuleFlag(StringRef Key) const { 3238bfde891SManman Ren SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 3248bfde891SManman Ren getModuleFlagsMetadata(ModuleFlags); 3253ad5c962SBenjamin Kramer for (const ModuleFlagEntry &MFE : ModuleFlags) { 3268bfde891SManman Ren if (Key == MFE.Key->getString()) 3278bfde891SManman Ren return MFE.Val; 3288bfde891SManman Ren } 329c620761cSCraig Topper return nullptr; 3308bfde891SManman Ren } 3318bfde891SManman Ren 332ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that 333ef860a24SChandler Carruth /// represents module-level flags. This method returns null if there are no 334ef860a24SChandler Carruth /// module-level flags. 335ef860a24SChandler Carruth NamedMDNode *Module::getModuleFlagsMetadata() const { 336ef860a24SChandler Carruth return getNamedMetadata("llvm.module.flags"); 337ef860a24SChandler Carruth } 338ef860a24SChandler Carruth 339ef860a24SChandler Carruth /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 340ef860a24SChandler Carruth /// represents module-level flags. If module-level flags aren't found, it 341ef860a24SChandler Carruth /// creates the named metadata that contains them. 342ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 343ef860a24SChandler Carruth return getOrInsertNamedMetadata("llvm.module.flags"); 344ef860a24SChandler Carruth } 345ef860a24SChandler Carruth 346ef860a24SChandler Carruth /// addModuleFlag - Add a module-level flag to the module-level flags 347ef860a24SChandler Carruth /// metadata. It will create the module-level flags named metadata if it doesn't 348ef860a24SChandler Carruth /// already exist. 349ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 3505bf8fef5SDuncan P. N. Exon Smith Metadata *Val) { 351ef860a24SChandler Carruth Type *Int32Ty = Type::getInt32Ty(Context); 3525bf8fef5SDuncan P. N. Exon Smith Metadata *Ops[3] = { 3535bf8fef5SDuncan P. N. Exon Smith ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)), 3545bf8fef5SDuncan P. N. Exon Smith MDString::get(Context, Key), Val}; 355ef860a24SChandler Carruth getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 356ef860a24SChandler Carruth } 357ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 3585bf8fef5SDuncan P. N. Exon Smith Constant *Val) { 3595bf8fef5SDuncan P. N. Exon Smith addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val)); 3605bf8fef5SDuncan P. N. Exon Smith } 3615bf8fef5SDuncan P. N. Exon Smith void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 362ef860a24SChandler Carruth uint32_t Val) { 363ef860a24SChandler Carruth Type *Int32Ty = Type::getInt32Ty(Context); 364ef860a24SChandler Carruth addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 365ef860a24SChandler Carruth } 366ef860a24SChandler Carruth void Module::addModuleFlag(MDNode *Node) { 367ef860a24SChandler Carruth assert(Node->getNumOperands() == 3 && 368ef860a24SChandler Carruth "Invalid number of operands for module flag!"); 3695bf8fef5SDuncan P. N. Exon Smith assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) && 370ef860a24SChandler Carruth isa<MDString>(Node->getOperand(1)) && 371ef860a24SChandler Carruth "Invalid operand types for module flag!"); 372ef860a24SChandler Carruth getOrInsertModuleFlagsMetadata()->addOperand(Node); 373ef860a24SChandler Carruth } 374ef860a24SChandler Carruth 37501909b4eSHiroshi Yamauchi void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key, 37601909b4eSHiroshi Yamauchi Metadata *Val) { 37701909b4eSHiroshi Yamauchi NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata(); 37801909b4eSHiroshi Yamauchi // Replace the flag if it already exists. 37901909b4eSHiroshi Yamauchi for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) { 38001909b4eSHiroshi Yamauchi MDNode *Flag = ModFlags->getOperand(I); 38101909b4eSHiroshi Yamauchi ModFlagBehavior MFB; 38201909b4eSHiroshi Yamauchi MDString *K = nullptr; 38301909b4eSHiroshi Yamauchi Metadata *V = nullptr; 38401909b4eSHiroshi Yamauchi if (isValidModuleFlag(*Flag, MFB, K, V) && K->getString() == Key) { 38501909b4eSHiroshi Yamauchi Flag->replaceOperandWith(2, Val); 38601909b4eSHiroshi Yamauchi return; 38701909b4eSHiroshi Yamauchi } 38801909b4eSHiroshi Yamauchi } 38901909b4eSHiroshi Yamauchi addModuleFlag(Behavior, Key, Val); 39001909b4eSHiroshi Yamauchi } 39101909b4eSHiroshi Yamauchi 392f863ee29SRafael Espindola void Module::setDataLayout(StringRef Desc) { 393248ac139SRafael Espindola DL.reset(Desc); 394f863ee29SRafael Espindola } 395f863ee29SRafael Espindola 39646a43556SMehdi Amini void Module::setDataLayout(const DataLayout &Other) { DL = Other; } 397f863ee29SRafael Espindola 39846a43556SMehdi Amini const DataLayout &Module::getDataLayout() const { return DL; } 399f863ee29SRafael Espindola 4005992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator*() const { 4015992a72bSAdrian Prantl return cast<DICompileUnit>(CUs->getOperand(Idx)); 4025992a72bSAdrian Prantl } 4035992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator->() const { 4045992a72bSAdrian Prantl return cast<DICompileUnit>(CUs->getOperand(Idx)); 4055992a72bSAdrian Prantl } 4065992a72bSAdrian Prantl 4075992a72bSAdrian Prantl void Module::debug_compile_units_iterator::SkipNoDebugCUs() { 4085992a72bSAdrian Prantl while (CUs && (Idx < CUs->getNumOperands()) && 4095992a72bSAdrian Prantl ((*this)->getEmissionKind() == DICompileUnit::NoDebug)) 4105992a72bSAdrian Prantl ++Idx; 4115992a72bSAdrian Prantl } 4125992a72bSAdrian Prantl 413285cf9a8SReid Kleckner iterator_range<Module::global_object_iterator> Module::global_objects() { 414285cf9a8SReid Kleckner return concat<GlobalObject>(functions(), globals()); 415285cf9a8SReid Kleckner } 416285cf9a8SReid Kleckner iterator_range<Module::const_global_object_iterator> 417285cf9a8SReid Kleckner Module::global_objects() const { 418285cf9a8SReid Kleckner return concat<const GlobalObject>(functions(), globals()); 419285cf9a8SReid Kleckner } 420285cf9a8SReid Kleckner 421285cf9a8SReid Kleckner iterator_range<Module::global_value_iterator> Module::global_values() { 422285cf9a8SReid Kleckner return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs()); 423285cf9a8SReid Kleckner } 424285cf9a8SReid Kleckner iterator_range<Module::const_global_value_iterator> 425285cf9a8SReid Kleckner Module::global_values() const { 426285cf9a8SReid Kleckner return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs()); 427285cf9a8SReid Kleckner } 428285cf9a8SReid Kleckner 429ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 430ef860a24SChandler Carruth // Methods to control the materialization of GlobalValues in the Module. 431ef860a24SChandler Carruth // 432ef860a24SChandler Carruth void Module::setMaterializer(GVMaterializer *GVM) { 433ef860a24SChandler Carruth assert(!Materializer && 434c4a03483SRafael Espindola "Module already has a GVMaterializer. Call materializeAll" 435ef860a24SChandler Carruth " to clear it out before setting another one."); 436ef860a24SChandler Carruth Materializer.reset(GVM); 437ef860a24SChandler Carruth } 438ef860a24SChandler Carruth 4397f00d0a1SPeter Collingbourne Error Module::materialize(GlobalValue *GV) { 4402b11ad4fSRafael Espindola if (!Materializer) 4417f00d0a1SPeter Collingbourne return Error::success(); 4422b11ad4fSRafael Espindola 4435a52e6dcSRafael Espindola return Materializer->materialize(GV); 444ef860a24SChandler Carruth } 445ef860a24SChandler Carruth 4467f00d0a1SPeter Collingbourne Error Module::materializeAll() { 447ef860a24SChandler Carruth if (!Materializer) 4487f00d0a1SPeter Collingbourne return Error::success(); 449257a3536SRafael Espindola std::unique_ptr<GVMaterializer> M = std::move(Materializer); 450257a3536SRafael Espindola return M->materializeModule(); 451ef860a24SChandler Carruth } 452ef860a24SChandler Carruth 4537f00d0a1SPeter Collingbourne Error Module::materializeMetadata() { 454cba833a0SRafael Espindola if (!Materializer) 4557f00d0a1SPeter Collingbourne return Error::success(); 456cba833a0SRafael Espindola return Materializer->materializeMetadata(); 457cba833a0SRafael Espindola } 458cba833a0SRafael Espindola 459ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 460ef860a24SChandler Carruth // Other module related stuff. 461ef860a24SChandler Carruth // 462ef860a24SChandler Carruth 4632fa1e43aSRafael Espindola std::vector<StructType *> Module::getIdentifiedStructTypes() const { 4642fa1e43aSRafael Espindola // If we have a materializer, it is possible that some unread function 4652fa1e43aSRafael Espindola // uses a type that is currently not visible to a TypeFinder, so ask 4662fa1e43aSRafael Espindola // the materializer which types it created. 4672fa1e43aSRafael Espindola if (Materializer) 4682fa1e43aSRafael Espindola return Materializer->getIdentifiedStructTypes(); 4692fa1e43aSRafael Espindola 4702fa1e43aSRafael Espindola std::vector<StructType *> Ret; 4712fa1e43aSRafael Espindola TypeFinder SrcStructTypes; 4722fa1e43aSRafael Espindola SrcStructTypes.run(*this, true); 4732fa1e43aSRafael Espindola Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end()); 4742fa1e43aSRafael Espindola return Ret; 4752fa1e43aSRafael Espindola } 476ef860a24SChandler Carruth 47704790d9cSJeroen Dobbelaere std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id, 47804790d9cSJeroen Dobbelaere const FunctionType *Proto) { 47904790d9cSJeroen Dobbelaere auto Encode = [&BaseName](unsigned Suffix) { 48004790d9cSJeroen Dobbelaere return (Twine(BaseName) + "." + Twine(Suffix)).str(); 48104790d9cSJeroen Dobbelaere }; 48204790d9cSJeroen Dobbelaere 48304790d9cSJeroen Dobbelaere { 48404790d9cSJeroen Dobbelaere // fast path - the prototype is already known 48504790d9cSJeroen Dobbelaere auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0}); 48604790d9cSJeroen Dobbelaere if (!UinItInserted.second) 48704790d9cSJeroen Dobbelaere return Encode(UinItInserted.first->second); 48804790d9cSJeroen Dobbelaere } 48904790d9cSJeroen Dobbelaere 49004790d9cSJeroen Dobbelaere // Not known yet. A new entry was created with index 0. Check if there already 49104790d9cSJeroen Dobbelaere // exists a matching declaration, or select a new entry. 49204790d9cSJeroen Dobbelaere 49304790d9cSJeroen Dobbelaere // Start looking for names with the current known maximum count (or 0). 49404790d9cSJeroen Dobbelaere auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0}); 49504790d9cSJeroen Dobbelaere unsigned Count = NiidItInserted.first->second; 49604790d9cSJeroen Dobbelaere 49704790d9cSJeroen Dobbelaere // This might be slow if a whole population of intrinsics already existed, but 49804790d9cSJeroen Dobbelaere // we cache the values for later usage. 49904790d9cSJeroen Dobbelaere std::string NewName; 50004790d9cSJeroen Dobbelaere while (true) { 50104790d9cSJeroen Dobbelaere NewName = Encode(Count); 50204790d9cSJeroen Dobbelaere GlobalValue *F = getNamedValue(NewName); 50304790d9cSJeroen Dobbelaere if (!F) { 50404790d9cSJeroen Dobbelaere // Reserve this entry for the new proto 50504790d9cSJeroen Dobbelaere UniquedIntrinsicNames[{Id, Proto}] = Count; 50604790d9cSJeroen Dobbelaere break; 50704790d9cSJeroen Dobbelaere } 50804790d9cSJeroen Dobbelaere 50904790d9cSJeroen Dobbelaere // A declaration with this name already exists. Remember it. 5104e601325SArthur Eubanks FunctionType *FT = dyn_cast<FunctionType>(F->getValueType()); 51104790d9cSJeroen Dobbelaere auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count}); 51204790d9cSJeroen Dobbelaere if (FT == Proto) { 51304790d9cSJeroen Dobbelaere // It was a declaration for our prototype. This entry was allocated in the 51404790d9cSJeroen Dobbelaere // beginning. Update the count to match the existing declaration. 51504790d9cSJeroen Dobbelaere UinItInserted.first->second = Count; 51604790d9cSJeroen Dobbelaere break; 51704790d9cSJeroen Dobbelaere } 51804790d9cSJeroen Dobbelaere 51904790d9cSJeroen Dobbelaere ++Count; 52004790d9cSJeroen Dobbelaere } 52104790d9cSJeroen Dobbelaere 52204790d9cSJeroen Dobbelaere NiidItInserted.first->second = Count + 1; 52304790d9cSJeroen Dobbelaere 52404790d9cSJeroen Dobbelaere return NewName; 52504790d9cSJeroen Dobbelaere } 52604790d9cSJeroen Dobbelaere 527ef860a24SChandler Carruth // dropAllReferences() - This function causes all the subelements to "let go" 528ef860a24SChandler Carruth // of all references that they are maintaining. This allows one to 'delete' a 529ef860a24SChandler Carruth // whole module at a time, even though there may be circular references... first 530ef860a24SChandler Carruth // all references are dropped, and all use counts go to zero. Then everything 531ef860a24SChandler Carruth // is deleted for real. Note that no operations are valid on an object that 532ef860a24SChandler Carruth // has "dropped all references", except operator delete. 533ef860a24SChandler Carruth // 534ef860a24SChandler Carruth void Module::dropAllReferences() { 5353374910fSDavid Majnemer for (Function &F : *this) 5363374910fSDavid Majnemer F.dropAllReferences(); 537ef860a24SChandler Carruth 5383374910fSDavid Majnemer for (GlobalVariable &GV : globals()) 5393374910fSDavid Majnemer GV.dropAllReferences(); 540ef860a24SChandler Carruth 5413374910fSDavid Majnemer for (GlobalAlias &GA : aliases()) 5423374910fSDavid Majnemer GA.dropAllReferences(); 543a1feff70SDmitry Polukhin 544a1feff70SDmitry Polukhin for (GlobalIFunc &GIF : ifuncs()) 545a1feff70SDmitry Polukhin GIF.dropAllReferences(); 546ef860a24SChandler Carruth } 5470915c047SDiego Novillo 548ac6081cbSNirav Dave unsigned Module::getNumberRegisterParameters() const { 549ac6081cbSNirav Dave auto *Val = 550ac6081cbSNirav Dave cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters")); 551ac6081cbSNirav Dave if (!Val) 552ac6081cbSNirav Dave return 0; 553ac6081cbSNirav Dave return cast<ConstantInt>(Val->getValue())->getZExtValue(); 554ac6081cbSNirav Dave } 555ac6081cbSNirav Dave 5560915c047SDiego Novillo unsigned Module::getDwarfVersion() const { 5575bf8fef5SDuncan P. N. Exon Smith auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version")); 5580915c047SDiego Novillo if (!Val) 55912d2c120SReid Kleckner return 0; 56012d2c120SReid Kleckner return cast<ConstantInt>(Val->getValue())->getZExtValue(); 56112d2c120SReid Kleckner } 56212d2c120SReid Kleckner 563aa842896SIgor Kudrin bool Module::isDwarf64() const { 564aa842896SIgor Kudrin auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64")); 565aa842896SIgor Kudrin return Val && cast<ConstantInt>(Val->getValue())->isOne(); 566aa842896SIgor Kudrin } 567aa842896SIgor Kudrin 56812d2c120SReid Kleckner unsigned Module::getCodeViewFlag() const { 56912d2c120SReid Kleckner auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView")); 57012d2c120SReid Kleckner if (!Val) 57112d2c120SReid Kleckner return 0; 5725bf8fef5SDuncan P. N. Exon Smith return cast<ConstantInt>(Val->getValue())->getZExtValue(); 5730915c047SDiego Novillo } 574dad0a645SDavid Majnemer 57520ad206bSMircea Trofin unsigned Module::getInstructionCount() const { 576e49374d0SJessica Paquette unsigned NumInstrs = 0; 57720ad206bSMircea Trofin for (const Function &F : FunctionList) 578e49374d0SJessica Paquette NumInstrs += F.getInstructionCount(); 579e49374d0SJessica Paquette return NumInstrs; 580e49374d0SJessica Paquette } 581e49374d0SJessica Paquette 582dad0a645SDavid Majnemer Comdat *Module::getOrInsertComdat(StringRef Name) { 5835106ce78SDavid Blaikie auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first; 584dad0a645SDavid Majnemer Entry.second.Name = &Entry; 585dad0a645SDavid Majnemer return &Entry.second; 586dad0a645SDavid Majnemer } 587771c132eSJustin Hibbits 588771c132eSJustin Hibbits PICLevel::Level Module::getPICLevel() const { 5895bf8fef5SDuncan P. N. Exon Smith auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level")); 590771c132eSJustin Hibbits 591083ca9bbSHans Wennborg if (!Val) 5924cccc488SDavide Italiano return PICLevel::NotPIC; 593771c132eSJustin Hibbits 5945bf8fef5SDuncan P. N. Exon Smith return static_cast<PICLevel::Level>( 5955bf8fef5SDuncan P. N. Exon Smith cast<ConstantInt>(Val->getValue())->getZExtValue()); 596771c132eSJustin Hibbits } 597771c132eSJustin Hibbits 598771c132eSJustin Hibbits void Module::setPICLevel(PICLevel::Level PL) { 5992db1369cSTeresa Johnson addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL); 600771c132eSJustin Hibbits } 601ecb05e51SEaswaran Raman 60246d47b8cSSriraman Tallam PIELevel::Level Module::getPIELevel() const { 60346d47b8cSSriraman Tallam auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level")); 60446d47b8cSSriraman Tallam 60546d47b8cSSriraman Tallam if (!Val) 60646d47b8cSSriraman Tallam return PIELevel::Default; 60746d47b8cSSriraman Tallam 60846d47b8cSSriraman Tallam return static_cast<PIELevel::Level>( 60946d47b8cSSriraman Tallam cast<ConstantInt>(Val->getValue())->getZExtValue()); 61046d47b8cSSriraman Tallam } 61146d47b8cSSriraman Tallam 61246d47b8cSSriraman Tallam void Module::setPIELevel(PIELevel::Level PL) { 6132db1369cSTeresa Johnson addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL); 61446d47b8cSSriraman Tallam } 61546d47b8cSSriraman Tallam 6163dea3f9eSCaroline Tice Optional<CodeModel::Model> Module::getCodeModel() const { 6173dea3f9eSCaroline Tice auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model")); 6183dea3f9eSCaroline Tice 6193dea3f9eSCaroline Tice if (!Val) 6203dea3f9eSCaroline Tice return None; 6213dea3f9eSCaroline Tice 6223dea3f9eSCaroline Tice return static_cast<CodeModel::Model>( 6233dea3f9eSCaroline Tice cast<ConstantInt>(Val->getValue())->getZExtValue()); 6243dea3f9eSCaroline Tice } 6253dea3f9eSCaroline Tice 6263dea3f9eSCaroline Tice void Module::setCodeModel(CodeModel::Model CL) { 6273dea3f9eSCaroline Tice // Linking object files with different code models is undefined behavior 6283dea3f9eSCaroline Tice // because the compiler would have to generate additional code (to span 6293dea3f9eSCaroline Tice // longer jumps) if a larger code model is used with a smaller one. 6303dea3f9eSCaroline Tice // Therefore we will treat attempts to mix code models as an error. 6313dea3f9eSCaroline Tice addModuleFlag(ModFlagBehavior::Error, "Code Model", CL); 6323dea3f9eSCaroline Tice } 6333dea3f9eSCaroline Tice 634a6ff69f6SRong Xu void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) { 635a6ff69f6SRong Xu if (Kind == ProfileSummary::PSK_CSInstr) 63601909b4eSHiroshi Yamauchi setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M); 637a6ff69f6SRong Xu else 63801909b4eSHiroshi Yamauchi setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M); 63926628d30SEaswaran Raman } 64026628d30SEaswaran Raman 64193dc1b5bSWei Wang Metadata *Module::getProfileSummary(bool IsCS) const { 642a6ff69f6SRong Xu return (IsCS ? getModuleFlag("CSProfileSummary") 643a6ff69f6SRong Xu : getModuleFlag("ProfileSummary")); 64426628d30SEaswaran Raman } 645b35cc691STeresa Johnson 646fd09f12fSserge-sans-paille bool Module::getSemanticInterposition() const { 647fd09f12fSserge-sans-paille Metadata *MF = getModuleFlag("SemanticInterposition"); 648fd09f12fSserge-sans-paille 649fd09f12fSserge-sans-paille auto *Val = cast_or_null<ConstantAsMetadata>(MF); 650fd09f12fSserge-sans-paille if (!Val) 651fd09f12fSserge-sans-paille return false; 652fd09f12fSserge-sans-paille 653fd09f12fSserge-sans-paille return cast<ConstantInt>(Val->getValue())->getZExtValue(); 654fd09f12fSserge-sans-paille } 655fd09f12fSserge-sans-paille 656fd09f12fSserge-sans-paille void Module::setSemanticInterposition(bool SI) { 657fd09f12fSserge-sans-paille addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI); 658fd09f12fSserge-sans-paille } 659fd09f12fSserge-sans-paille 660e2dcf7c3SPeter Collingbourne void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) { 661e2dcf7c3SPeter Collingbourne OwnedMemoryBuffer = std::move(MB); 662e2dcf7c3SPeter Collingbourne } 663e2dcf7c3SPeter Collingbourne 664609f8c01SSriraman Tallam bool Module::getRtLibUseGOT() const { 665609f8c01SSriraman Tallam auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT")); 666609f8c01SSriraman Tallam return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0); 667609f8c01SSriraman Tallam } 668609f8c01SSriraman Tallam 669609f8c01SSriraman Tallam void Module::setRtLibUseGOT() { 670609f8c01SSriraman Tallam addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1); 671609f8c01SSriraman Tallam } 672609f8c01SSriraman Tallam 6736398903aSMomchil Velikov UWTableKind Module::getUwtable() const { 6746398903aSMomchil Velikov if (auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable"))) 6756398903aSMomchil Velikov return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue()); 6766398903aSMomchil Velikov return UWTableKind::None; 677775a9483SFangrui Song } 678775a9483SFangrui Song 6796398903aSMomchil Velikov void Module::setUwtable(UWTableKind Kind) { 6806398903aSMomchil Velikov addModuleFlag(ModFlagBehavior::Max, "uwtable", uint32_t(Kind)); 6816398903aSMomchil Velikov } 682775a9483SFangrui Song 6832786e673SFangrui Song FramePointerKind Module::getFramePointer() const { 6842786e673SFangrui Song auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer")); 6852786e673SFangrui Song return static_cast<FramePointerKind>( 6862786e673SFangrui Song Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0); 6872786e673SFangrui Song } 6882786e673SFangrui Song 6892786e673SFangrui Song void Module::setFramePointer(FramePointerKind Kind) { 6902786e673SFangrui Song addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind)); 6912786e673SFangrui Song } 6922786e673SFangrui Song 693033138eaSNick Desaulniers StringRef Module::getStackProtectorGuard() const { 694033138eaSNick Desaulniers Metadata *MD = getModuleFlag("stack-protector-guard"); 695033138eaSNick Desaulniers if (auto *MDS = dyn_cast_or_null<MDString>(MD)) 696033138eaSNick Desaulniers return MDS->getString(); 697033138eaSNick Desaulniers return {}; 698033138eaSNick Desaulniers } 699033138eaSNick Desaulniers 700033138eaSNick Desaulniers void Module::setStackProtectorGuard(StringRef Kind) { 701033138eaSNick Desaulniers MDString *ID = MDString::get(getContext(), Kind); 702033138eaSNick Desaulniers addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID); 703033138eaSNick Desaulniers } 704033138eaSNick Desaulniers 705033138eaSNick Desaulniers StringRef Module::getStackProtectorGuardReg() const { 706033138eaSNick Desaulniers Metadata *MD = getModuleFlag("stack-protector-guard-reg"); 707033138eaSNick Desaulniers if (auto *MDS = dyn_cast_or_null<MDString>(MD)) 708033138eaSNick Desaulniers return MDS->getString(); 709033138eaSNick Desaulniers return {}; 710033138eaSNick Desaulniers } 711033138eaSNick Desaulniers 712033138eaSNick Desaulniers void Module::setStackProtectorGuardReg(StringRef Reg) { 713033138eaSNick Desaulniers MDString *ID = MDString::get(getContext(), Reg); 714033138eaSNick Desaulniers addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID); 715033138eaSNick Desaulniers } 716033138eaSNick Desaulniers 717033138eaSNick Desaulniers int Module::getStackProtectorGuardOffset() const { 718033138eaSNick Desaulniers Metadata *MD = getModuleFlag("stack-protector-guard-offset"); 719033138eaSNick Desaulniers if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD)) 720033138eaSNick Desaulniers return CI->getSExtValue(); 721033138eaSNick Desaulniers return INT_MAX; 722033138eaSNick Desaulniers } 723033138eaSNick Desaulniers 724033138eaSNick Desaulniers void Module::setStackProtectorGuardOffset(int Offset) { 725033138eaSNick Desaulniers addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset); 726033138eaSNick Desaulniers } 727033138eaSNick Desaulniers 7283787ee45SNick Desaulniers unsigned Module::getOverrideStackAlignment() const { 7293787ee45SNick Desaulniers Metadata *MD = getModuleFlag("override-stack-alignment"); 7303787ee45SNick Desaulniers if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD)) 7313787ee45SNick Desaulniers return CI->getZExtValue(); 7323787ee45SNick Desaulniers return 0; 7333787ee45SNick Desaulniers } 7343787ee45SNick Desaulniers 7353787ee45SNick Desaulniers void Module::setOverrideStackAlignment(unsigned Align) { 7363787ee45SNick Desaulniers addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align); 7373787ee45SNick Desaulniers } 7383787ee45SNick Desaulniers 739116c1beaSAlex Lorenz static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name) { 740afa75d78SAlex Lorenz SmallVector<unsigned, 3> Entries; 741afa75d78SAlex Lorenz Entries.push_back(V.getMajor()); 742afa75d78SAlex Lorenz if (auto Minor = V.getMinor()) { 743afa75d78SAlex Lorenz Entries.push_back(*Minor); 744afa75d78SAlex Lorenz if (auto Subminor = V.getSubminor()) 745afa75d78SAlex Lorenz Entries.push_back(*Subminor); 746afa75d78SAlex Lorenz // Ignore the 'build' component as it can't be represented in the object 747afa75d78SAlex Lorenz // file. 748afa75d78SAlex Lorenz } 749116c1beaSAlex Lorenz M.addModuleFlag(Module::ModFlagBehavior::Warning, Name, 750116c1beaSAlex Lorenz ConstantDataArray::get(M.getContext(), Entries)); 751116c1beaSAlex Lorenz } 752116c1beaSAlex Lorenz 753116c1beaSAlex Lorenz void Module::setSDKVersion(const VersionTuple &V) { 754116c1beaSAlex Lorenz addSDKVersionMD(V, *this, "SDK Version"); 755afa75d78SAlex Lorenz } 756afa75d78SAlex Lorenz 7570756aa39SAlex Lorenz static VersionTuple getSDKVersionMD(Metadata *MD) { 7580756aa39SAlex Lorenz auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD); 759afa75d78SAlex Lorenz if (!CM) 760afa75d78SAlex Lorenz return {}; 761afa75d78SAlex Lorenz auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue()); 762afa75d78SAlex Lorenz if (!Arr) 763afa75d78SAlex Lorenz return {}; 764afa75d78SAlex Lorenz auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> { 765afa75d78SAlex Lorenz if (Index >= Arr->getNumElements()) 766afa75d78SAlex Lorenz return None; 767afa75d78SAlex Lorenz return (unsigned)Arr->getElementAsInteger(Index); 768afa75d78SAlex Lorenz }; 769afa75d78SAlex Lorenz auto Major = getVersionComponent(0); 770afa75d78SAlex Lorenz if (!Major) 771afa75d78SAlex Lorenz return {}; 772afa75d78SAlex Lorenz VersionTuple Result = VersionTuple(*Major); 773afa75d78SAlex Lorenz if (auto Minor = getVersionComponent(1)) { 774afa75d78SAlex Lorenz Result = VersionTuple(*Major, *Minor); 775afa75d78SAlex Lorenz if (auto Subminor = getVersionComponent(2)) { 776afa75d78SAlex Lorenz Result = VersionTuple(*Major, *Minor, *Subminor); 777afa75d78SAlex Lorenz } 778afa75d78SAlex Lorenz } 779afa75d78SAlex Lorenz return Result; 780afa75d78SAlex Lorenz } 781afa75d78SAlex Lorenz 7820756aa39SAlex Lorenz VersionTuple Module::getSDKVersion() const { 7830756aa39SAlex Lorenz return getSDKVersionMD(getModuleFlag("SDK Version")); 7840756aa39SAlex Lorenz } 7850756aa39SAlex Lorenz 786b35cc691STeresa Johnson GlobalVariable *llvm::collectUsedGlobalVariables( 7873adb89bbSFangrui Song const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) { 7883adb89bbSFangrui Song const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used"; 7893adb89bbSFangrui Song GlobalVariable *GV = M.getGlobalVariable(Name); 7903adb89bbSFangrui Song if (!GV || !GV->hasInitializer()) 7913adb89bbSFangrui Song return GV; 7923adb89bbSFangrui Song 7933adb89bbSFangrui Song const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 7943adb89bbSFangrui Song for (Value *Op : Init->operands()) { 7953adb89bbSFangrui Song GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts()); 7963adb89bbSFangrui Song Vec.push_back(G); 7973adb89bbSFangrui Song } 7983adb89bbSFangrui Song return GV; 7993adb89bbSFangrui Song } 8003adb89bbSFangrui Song 8016c27c61dSHiroshi Yamauchi void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) { 8026c27c61dSHiroshi Yamauchi if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) { 8036c27c61dSHiroshi Yamauchi std::unique_ptr<ProfileSummary> ProfileSummary( 8046c27c61dSHiroshi Yamauchi ProfileSummary::getFromMD(SummaryMD)); 8056c27c61dSHiroshi Yamauchi if (ProfileSummary) { 8066c27c61dSHiroshi Yamauchi if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample || 8076c27c61dSHiroshi Yamauchi !ProfileSummary->isPartialProfile()) 8086c27c61dSHiroshi Yamauchi return; 8096c27c61dSHiroshi Yamauchi uint64_t BlockCount = Index.getBlockCount(); 8106c27c61dSHiroshi Yamauchi uint32_t NumCounts = ProfileSummary->getNumCounts(); 8116c27c61dSHiroshi Yamauchi if (!NumCounts) 8126c27c61dSHiroshi Yamauchi return; 8136c27c61dSHiroshi Yamauchi double Ratio = (double)BlockCount / NumCounts; 8146c27c61dSHiroshi Yamauchi ProfileSummary->setPartialProfileRatio(Ratio); 8156c27c61dSHiroshi Yamauchi setProfileSummary(ProfileSummary->getMD(getContext()), 8166c27c61dSHiroshi Yamauchi ProfileSummary::PSK_Sample); 8176c27c61dSHiroshi Yamauchi } 8186c27c61dSHiroshi Yamauchi } 8196c27c61dSHiroshi Yamauchi } 8200756aa39SAlex Lorenz 8210756aa39SAlex Lorenz StringRef Module::getDarwinTargetVariantTriple() const { 8220756aa39SAlex Lorenz if (const auto *MD = getModuleFlag("darwin.target_variant.triple")) 8230756aa39SAlex Lorenz return cast<MDString>(MD)->getString(); 8240756aa39SAlex Lorenz return ""; 8250756aa39SAlex Lorenz } 8260756aa39SAlex Lorenz 827116c1beaSAlex Lorenz void Module::setDarwinTargetVariantTriple(StringRef T) { 828116c1beaSAlex Lorenz addModuleFlag(ModFlagBehavior::Override, "darwin.target_variant.triple", 829116c1beaSAlex Lorenz MDString::get(getContext(), T)); 830116c1beaSAlex Lorenz } 831116c1beaSAlex Lorenz 8320756aa39SAlex Lorenz VersionTuple Module::getDarwinTargetVariantSDKVersion() const { 8330756aa39SAlex Lorenz return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version")); 8340756aa39SAlex Lorenz } 835116c1beaSAlex Lorenz 836116c1beaSAlex Lorenz void Module::setDarwinTargetVariantSDKVersion(VersionTuple Version) { 837116c1beaSAlex Lorenz addSDKVersionMD(Version, *this, "darwin.target_variant.SDK Version"); 838116c1beaSAlex Lorenz } 839