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" 16b35cc691STeresa Johnson #include "llvm/ADT/SmallPtrSet.h" 17ef860a24SChandler Carruth #include "llvm/ADT/SmallString.h" 18eba7e4ecSEugene Zelenko #include "llvm/ADT/SmallVector.h" 19eba7e4ecSEugene Zelenko #include "llvm/ADT/StringMap.h" 20eba7e4ecSEugene Zelenko #include "llvm/ADT/StringRef.h" 21eba7e4ecSEugene Zelenko #include "llvm/ADT/Twine.h" 22eba7e4ecSEugene Zelenko #include "llvm/IR/Attributes.h" 23eba7e4ecSEugene Zelenko #include "llvm/IR/Comdat.h" 249fb823bbSChandler Carruth #include "llvm/IR/Constants.h" 25eba7e4ecSEugene Zelenko #include "llvm/IR/DataLayout.h" 265992a72bSAdrian Prantl #include "llvm/IR/DebugInfoMetadata.h" 276bda14b3SChandler Carruth #include "llvm/IR/DerivedTypes.h" 28eba7e4ecSEugene Zelenko #include "llvm/IR/Function.h" 296bda14b3SChandler Carruth #include "llvm/IR/GVMaterializer.h" 30eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalAlias.h" 31eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalIFunc.h" 32eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalValue.h" 33eba7e4ecSEugene Zelenko #include "llvm/IR/GlobalVariable.h" 349fb823bbSChandler Carruth #include "llvm/IR/LLVMContext.h" 35eba7e4ecSEugene Zelenko #include "llvm/IR/Metadata.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/Pass.h" 42eba7e4ecSEugene Zelenko #include "llvm/Support/Casting.h" 43eba7e4ecSEugene Zelenko #include "llvm/Support/CodeGen.h" 447f00d0a1SPeter Collingbourne #include "llvm/Support/Error.h" 45e2dcf7c3SPeter Collingbourne #include "llvm/Support/MemoryBuffer.h" 46144829d3SJF Bastien #include "llvm/Support/Path.h" 47144829d3SJF Bastien #include "llvm/Support/RandomNumberGenerator.h" 48afa75d78SAlex Lorenz #include "llvm/Support/VersionTuple.h" 49ef860a24SChandler Carruth #include <algorithm> 50eba7e4ecSEugene Zelenko #include <cassert> 51eba7e4ecSEugene Zelenko #include <cstdint> 52eba7e4ecSEugene Zelenko #include <memory> 53eba7e4ecSEugene Zelenko #include <utility> 54eba7e4ecSEugene Zelenko #include <vector> 55083ca9bbSHans Wennborg 56ef860a24SChandler Carruth using namespace llvm; 57ef860a24SChandler Carruth 58ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 59ef860a24SChandler Carruth // Methods to implement the globals and functions lists. 60ef860a24SChandler Carruth // 61ef860a24SChandler Carruth 62ef860a24SChandler Carruth // Explicit instantiations of SymbolTableListTraits since some of the methods 63ef860a24SChandler Carruth // are not in the public header file. 6437bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<Function>; 6537bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<GlobalVariable>; 6637bf678aSDuncan P. N. Exon Smith template class llvm::SymbolTableListTraits<GlobalAlias>; 67a1feff70SDmitry Polukhin template class llvm::SymbolTableListTraits<GlobalIFunc>; 68ef860a24SChandler Carruth 69ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 70ef860a24SChandler Carruth // Primitive Module methods. 71ef860a24SChandler Carruth // 72ef860a24SChandler Carruth 73ef860a24SChandler Carruth Module::Module(StringRef MID, LLVMContext &C) 7446ed9331SDavid Blaikie : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>()), 75*adcd0268SBenjamin Kramer Materializer(), ModuleID(std::string(MID)), 76*adcd0268SBenjamin Kramer SourceFileName(std::string(MID)), DL("") { 77ef860a24SChandler Carruth Context.addModule(this); 78ef860a24SChandler Carruth } 79ef860a24SChandler Carruth 80ef860a24SChandler Carruth Module::~Module() { 81ef860a24SChandler Carruth Context.removeModule(this); 82ef860a24SChandler Carruth dropAllReferences(); 83ef860a24SChandler Carruth GlobalList.clear(); 84ef860a24SChandler Carruth FunctionList.clear(); 85ef860a24SChandler Carruth AliasList.clear(); 86a1feff70SDmitry Polukhin IFuncList.clear(); 87ef860a24SChandler Carruth } 88ef860a24SChandler Carruth 89e14625faSSerge Guelton std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const { 90e6acbdc4SJF Bastien SmallString<32> Salt(P->getPassName()); 91e6acbdc4SJF Bastien 92e6acbdc4SJF Bastien // This RNG is guaranteed to produce the same random stream only 93e6acbdc4SJF Bastien // when the Module ID and thus the input filename is the same. This 94e6acbdc4SJF Bastien // might be problematic if the input filename extension changes 95e6acbdc4SJF Bastien // (e.g. from .c to .bc or .ll). 96e6acbdc4SJF Bastien // 97e6acbdc4SJF Bastien // We could store this salt in NamedMetadata, but this would make 98e6acbdc4SJF Bastien // the parameter non-const. This would unfortunately make this 99e6acbdc4SJF Bastien // interface unusable by any Machine passes, since they only have a 100e6acbdc4SJF Bastien // const reference to their IR Module. Alternatively we can always 101e6acbdc4SJF Bastien // store salt metadata from the Module constructor. 102e6acbdc4SJF Bastien Salt += sys::path::filename(getModuleIdentifier()); 103e6acbdc4SJF Bastien 104ad9bbc20SSerge Guelton return std::unique_ptr<RandomNumberGenerator>(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 114ef860a24SChandler Carruth /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 115ef860a24SChandler Carruth /// This ID is uniqued across modules in the current LLVMContext. 116ef860a24SChandler Carruth unsigned Module::getMDKindID(StringRef Name) const { 117ef860a24SChandler Carruth return Context.getMDKindID(Name); 118ef860a24SChandler Carruth } 119ef860a24SChandler Carruth 120ef860a24SChandler Carruth /// getMDKindNames - Populate client supplied SmallVector with the name for 121ef860a24SChandler Carruth /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 122ef860a24SChandler Carruth /// so it is filled in as an empty string. 123ef860a24SChandler Carruth void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 124ef860a24SChandler Carruth return Context.getMDKindNames(Result); 125ef860a24SChandler Carruth } 126ef860a24SChandler Carruth 1279303c246SSanjoy Das void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const { 1289303c246SSanjoy Das return Context.getOperandBundleTags(Result); 1299303c246SSanjoy Das } 130ef860a24SChandler Carruth 131ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 132ef860a24SChandler Carruth // Methods for easy access to the functions in the module. 133ef860a24SChandler Carruth // 134ef860a24SChandler Carruth 135ef860a24SChandler Carruth // getOrInsertFunction - Look up the specified function in the module symbol 136ef860a24SChandler Carruth // table. If it does not exist, add a prototype for the function and return 137ef860a24SChandler Carruth // it. This is nice because it allows most passes to get away with not handling 138ef860a24SChandler Carruth // the symbol table directly for this common task. 139ef860a24SChandler Carruth // 14013680223SJames Y Knight FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty, 141b518054bSReid Kleckner AttributeList AttributeList) { 142ef860a24SChandler Carruth // See if we have a definition for the specified function already. 143ef860a24SChandler Carruth GlobalValue *F = getNamedValue(Name); 144c620761cSCraig Topper if (!F) { 145ef860a24SChandler Carruth // Nope, add it 1466bcf2ba2SAlexander Richardson Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, 1476bcf2ba2SAlexander Richardson DL.getProgramAddressSpace(), Name); 148ef860a24SChandler Carruth if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 149ef860a24SChandler Carruth New->setAttributes(AttributeList); 150ef860a24SChandler Carruth FunctionList.push_back(New); 15113680223SJames Y Knight return {Ty, New}; // Return the new prototype. 152ef860a24SChandler Carruth } 153ef860a24SChandler Carruth 154ef860a24SChandler Carruth // If the function exists but has the wrong type, return a bitcast to the 155ef860a24SChandler Carruth // right type. 1566bcf2ba2SAlexander Richardson auto *PTy = PointerType::get(Ty, F->getAddressSpace()); 1576bcf2ba2SAlexander Richardson if (F->getType() != PTy) 15813680223SJames Y Knight return {Ty, ConstantExpr::getBitCast(F, PTy)}; 159ef860a24SChandler Carruth 160ef860a24SChandler Carruth // Otherwise, we just found the existing function or a prototype. 16113680223SJames Y Knight return {Ty, F}; 162ef860a24SChandler Carruth } 163ef860a24SChandler Carruth 16413680223SJames Y Knight FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) { 165b518054bSReid Kleckner return getOrInsertFunction(Name, Ty, AttributeList()); 166ef860a24SChandler Carruth } 167ef860a24SChandler Carruth 168ef860a24SChandler Carruth // getFunction - Look up the specified function in the module symbol table. 169ef860a24SChandler Carruth // If it does not exist, return null. 170ef860a24SChandler Carruth // 171ef860a24SChandler Carruth Function *Module::getFunction(StringRef Name) const { 172ef860a24SChandler Carruth return dyn_cast_or_null<Function>(getNamedValue(Name)); 173ef860a24SChandler Carruth } 174ef860a24SChandler Carruth 175ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 176ef860a24SChandler Carruth // Methods for easy access to the global variables in the module. 177ef860a24SChandler Carruth // 178ef860a24SChandler Carruth 179ef860a24SChandler Carruth /// getGlobalVariable - Look up the specified global variable in the module 180ef860a24SChandler Carruth /// symbol table. If it does not exist, return null. The type argument 181ef860a24SChandler Carruth /// should be the underlying type of the global, i.e., it should not have 182ef860a24SChandler Carruth /// the top-level PointerType, which represents the address of the global. 183ef860a24SChandler Carruth /// If AllowLocal is set to true, this function will return types that 184ef860a24SChandler Carruth /// have an local. By default, these types are not returned. 185ef860a24SChandler Carruth /// 1861dd20e65SCraig Topper GlobalVariable *Module::getGlobalVariable(StringRef Name, 1871dd20e65SCraig Topper bool AllowLocal) const { 188ef860a24SChandler Carruth if (GlobalVariable *Result = 189ef860a24SChandler Carruth dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 190ef860a24SChandler Carruth if (AllowLocal || !Result->hasLocalLinkage()) 191ef860a24SChandler Carruth return Result; 192c620761cSCraig Topper return nullptr; 193ef860a24SChandler Carruth } 194ef860a24SChandler Carruth 195ef860a24SChandler Carruth /// getOrInsertGlobal - Look up the specified global in the module symbol table. 196ef860a24SChandler Carruth /// 1. If it does not exist, add a declaration of the global and return it. 197ef860a24SChandler Carruth /// 2. Else, the global exists but has the wrong type: return the function 198ef860a24SChandler Carruth /// with a constantexpr cast to the right type. 1995200fdf0SMatt Arsenault /// 3. Finally, if the existing global is the correct declaration, return the 200ef860a24SChandler Carruth /// existing global. 2016bc98ad7SPhilip Pfaffe Constant *Module::getOrInsertGlobal( 2026bc98ad7SPhilip Pfaffe StringRef Name, Type *Ty, 2036bc98ad7SPhilip Pfaffe function_ref<GlobalVariable *()> CreateGlobalCallback) { 204ef860a24SChandler Carruth // See if we have a definition for the specified global already. 205ef860a24SChandler Carruth GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)); 2066bc98ad7SPhilip Pfaffe if (!GV) 2076bc98ad7SPhilip Pfaffe GV = CreateGlobalCallback(); 2086bc98ad7SPhilip Pfaffe assert(GV && "The CreateGlobalCallback is expected to create a global"); 209ef860a24SChandler Carruth 210ef860a24SChandler Carruth // If the variable exists but has the wrong type, return a bitcast to the 211ef860a24SChandler Carruth // right type. 21227e783e9SMatt Arsenault Type *GVTy = GV->getType(); 21327e783e9SMatt Arsenault PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace()); 214a90a340fSMatt Arsenault if (GVTy != PTy) 21527e783e9SMatt Arsenault return ConstantExpr::getBitCast(GV, PTy); 216ef860a24SChandler Carruth 217ef860a24SChandler Carruth // Otherwise, we just found the existing function or a prototype. 218ef860a24SChandler Carruth return GV; 219ef860a24SChandler Carruth } 220ef860a24SChandler Carruth 2216bc98ad7SPhilip Pfaffe // Overload to construct a global variable using its constructor's defaults. 2226bc98ad7SPhilip Pfaffe Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 2236bc98ad7SPhilip Pfaffe return getOrInsertGlobal(Name, Ty, [&] { 2246bc98ad7SPhilip Pfaffe return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 2256bc98ad7SPhilip Pfaffe nullptr, Name); 2266bc98ad7SPhilip Pfaffe }); 2276bc98ad7SPhilip Pfaffe } 2286bc98ad7SPhilip Pfaffe 229ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 230ef860a24SChandler Carruth // Methods for easy access to the global variables in the module. 231ef860a24SChandler Carruth // 232ef860a24SChandler Carruth 233ef860a24SChandler Carruth // getNamedAlias - Look up the specified global in the module symbol table. 234ef860a24SChandler Carruth // If it does not exist, return null. 235ef860a24SChandler Carruth // 236ef860a24SChandler Carruth GlobalAlias *Module::getNamedAlias(StringRef Name) const { 237ef860a24SChandler Carruth return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 238ef860a24SChandler Carruth } 239ef860a24SChandler Carruth 240a1feff70SDmitry Polukhin GlobalIFunc *Module::getNamedIFunc(StringRef Name) const { 241a1feff70SDmitry Polukhin return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name)); 242a1feff70SDmitry Polukhin } 243a1feff70SDmitry Polukhin 244ef860a24SChandler Carruth /// getNamedMetadata - Return the first NamedMDNode in the module with the 245ef860a24SChandler Carruth /// specified name. This method returns null if a NamedMDNode with the 246ef860a24SChandler Carruth /// specified name is not found. 247ef860a24SChandler Carruth NamedMDNode *Module::getNamedMetadata(const Twine &Name) const { 248ef860a24SChandler Carruth SmallString<256> NameData; 249ef860a24SChandler Carruth StringRef NameRef = Name.toStringRef(NameData); 250daab9227SBrian Gesiak return NamedMDSymTab.lookup(NameRef); 251ef860a24SChandler Carruth } 252ef860a24SChandler Carruth 253ef860a24SChandler Carruth /// getOrInsertNamedMetadata - Return the first named MDNode in the module 254ef860a24SChandler Carruth /// with the specified name. This method returns a new NamedMDNode if a 255ef860a24SChandler Carruth /// NamedMDNode with the specified name is not found. 256ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 257daab9227SBrian Gesiak NamedMDNode *&NMD = NamedMDSymTab[Name]; 258ef860a24SChandler Carruth if (!NMD) { 259ef860a24SChandler Carruth NMD = new NamedMDNode(Name); 260ef860a24SChandler Carruth NMD->setParent(this); 261ef860a24SChandler Carruth NamedMDList.push_back(NMD); 262ef860a24SChandler Carruth } 263ef860a24SChandler Carruth return NMD; 264ef860a24SChandler Carruth } 265ef860a24SChandler Carruth 266ef860a24SChandler Carruth /// eraseNamedMetadata - Remove the given NamedMDNode from this module and 267ef860a24SChandler Carruth /// delete it. 268ef860a24SChandler Carruth void Module::eraseNamedMetadata(NamedMDNode *NMD) { 269daab9227SBrian Gesiak NamedMDSymTab.erase(NMD->getName()); 27052888a67SDuncan P. N. Exon Smith NamedMDList.erase(NMD->getIterator()); 271ef860a24SChandler Carruth } 272ef860a24SChandler Carruth 2735bf8fef5SDuncan P. N. Exon Smith bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) { 274d7677e7aSDavid Majnemer if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) { 275af023adbSAlexey Samsonov uint64_t Val = Behavior->getLimitedValue(); 276af023adbSAlexey Samsonov if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) { 277af023adbSAlexey Samsonov MFB = static_cast<ModFlagBehavior>(Val); 278af023adbSAlexey Samsonov return true; 279af023adbSAlexey Samsonov } 280af023adbSAlexey Samsonov } 281af023adbSAlexey Samsonov return false; 282af023adbSAlexey Samsonov } 283af023adbSAlexey Samsonov 284ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the module flags in the provided vector. 285ef860a24SChandler Carruth void Module:: 286ef860a24SChandler Carruth getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 287ef860a24SChandler Carruth const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 288ef860a24SChandler Carruth if (!ModFlags) return; 289ef860a24SChandler Carruth 290de36e804SDuncan P. N. Exon Smith for (const MDNode *Flag : ModFlags->operands()) { 291af023adbSAlexey Samsonov ModFlagBehavior MFB; 292af023adbSAlexey Samsonov if (Flag->getNumOperands() >= 3 && 293af023adbSAlexey Samsonov isValidModFlagBehavior(Flag->getOperand(0), MFB) && 294d7677e7aSDavid Majnemer dyn_cast_or_null<MDString>(Flag->getOperand(1))) { 2958b4306ceSManman Ren // Check the operands of the MDNode before accessing the operands. 2968b4306ceSManman Ren // The verifier will actually catch these failures. 297ef860a24SChandler Carruth MDString *Key = cast<MDString>(Flag->getOperand(1)); 2985bf8fef5SDuncan P. N. Exon Smith Metadata *Val = Flag->getOperand(2); 299af023adbSAlexey Samsonov Flags.push_back(ModuleFlagEntry(MFB, Key, Val)); 300ef860a24SChandler Carruth } 301ef860a24SChandler Carruth } 3028b4306ceSManman Ren } 303ef860a24SChandler Carruth 3048bfde891SManman Ren /// Return the corresponding value if Key appears in module flags, otherwise 3058bfde891SManman Ren /// return null. 3065bf8fef5SDuncan P. N. Exon Smith Metadata *Module::getModuleFlag(StringRef Key) const { 3078bfde891SManman Ren SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 3088bfde891SManman Ren getModuleFlagsMetadata(ModuleFlags); 3093ad5c962SBenjamin Kramer for (const ModuleFlagEntry &MFE : ModuleFlags) { 3108bfde891SManman Ren if (Key == MFE.Key->getString()) 3118bfde891SManman Ren return MFE.Val; 3128bfde891SManman Ren } 313c620761cSCraig Topper return nullptr; 3148bfde891SManman Ren } 3158bfde891SManman Ren 316ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that 317ef860a24SChandler Carruth /// represents module-level flags. This method returns null if there are no 318ef860a24SChandler Carruth /// module-level flags. 319ef860a24SChandler Carruth NamedMDNode *Module::getModuleFlagsMetadata() const { 320ef860a24SChandler Carruth return getNamedMetadata("llvm.module.flags"); 321ef860a24SChandler Carruth } 322ef860a24SChandler Carruth 323ef860a24SChandler Carruth /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 324ef860a24SChandler Carruth /// represents module-level flags. If module-level flags aren't found, it 325ef860a24SChandler Carruth /// creates the named metadata that contains them. 326ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 327ef860a24SChandler Carruth return getOrInsertNamedMetadata("llvm.module.flags"); 328ef860a24SChandler Carruth } 329ef860a24SChandler Carruth 330ef860a24SChandler Carruth /// addModuleFlag - Add a module-level flag to the module-level flags 331ef860a24SChandler Carruth /// metadata. It will create the module-level flags named metadata if it doesn't 332ef860a24SChandler Carruth /// already exist. 333ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 3345bf8fef5SDuncan P. N. Exon Smith Metadata *Val) { 335ef860a24SChandler Carruth Type *Int32Ty = Type::getInt32Ty(Context); 3365bf8fef5SDuncan P. N. Exon Smith Metadata *Ops[3] = { 3375bf8fef5SDuncan P. N. Exon Smith ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)), 3385bf8fef5SDuncan P. N. Exon Smith MDString::get(Context, Key), Val}; 339ef860a24SChandler Carruth getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 340ef860a24SChandler Carruth } 341ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 3425bf8fef5SDuncan P. N. Exon Smith Constant *Val) { 3435bf8fef5SDuncan P. N. Exon Smith addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val)); 3445bf8fef5SDuncan P. N. Exon Smith } 3455bf8fef5SDuncan P. N. Exon Smith void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 346ef860a24SChandler Carruth uint32_t Val) { 347ef860a24SChandler Carruth Type *Int32Ty = Type::getInt32Ty(Context); 348ef860a24SChandler Carruth addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 349ef860a24SChandler Carruth } 350ef860a24SChandler Carruth void Module::addModuleFlag(MDNode *Node) { 351ef860a24SChandler Carruth assert(Node->getNumOperands() == 3 && 352ef860a24SChandler Carruth "Invalid number of operands for module flag!"); 3535bf8fef5SDuncan P. N. Exon Smith assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) && 354ef860a24SChandler Carruth isa<MDString>(Node->getOperand(1)) && 355ef860a24SChandler Carruth "Invalid operand types for module flag!"); 356ef860a24SChandler Carruth getOrInsertModuleFlagsMetadata()->addOperand(Node); 357ef860a24SChandler Carruth } 358ef860a24SChandler Carruth 359f863ee29SRafael Espindola void Module::setDataLayout(StringRef Desc) { 360248ac139SRafael Espindola DL.reset(Desc); 361f863ee29SRafael Espindola } 362f863ee29SRafael Espindola 36346a43556SMehdi Amini void Module::setDataLayout(const DataLayout &Other) { DL = Other; } 364f863ee29SRafael Espindola 36546a43556SMehdi Amini const DataLayout &Module::getDataLayout() const { return DL; } 366f863ee29SRafael Espindola 3675992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator*() const { 3685992a72bSAdrian Prantl return cast<DICompileUnit>(CUs->getOperand(Idx)); 3695992a72bSAdrian Prantl } 3705992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator->() const { 3715992a72bSAdrian Prantl return cast<DICompileUnit>(CUs->getOperand(Idx)); 3725992a72bSAdrian Prantl } 3735992a72bSAdrian Prantl 3745992a72bSAdrian Prantl void Module::debug_compile_units_iterator::SkipNoDebugCUs() { 3755992a72bSAdrian Prantl while (CUs && (Idx < CUs->getNumOperands()) && 3765992a72bSAdrian Prantl ((*this)->getEmissionKind() == DICompileUnit::NoDebug)) 3775992a72bSAdrian Prantl ++Idx; 3785992a72bSAdrian Prantl } 3795992a72bSAdrian Prantl 380285cf9a8SReid Kleckner iterator_range<Module::global_object_iterator> Module::global_objects() { 381285cf9a8SReid Kleckner return concat<GlobalObject>(functions(), globals()); 382285cf9a8SReid Kleckner } 383285cf9a8SReid Kleckner iterator_range<Module::const_global_object_iterator> 384285cf9a8SReid Kleckner Module::global_objects() const { 385285cf9a8SReid Kleckner return concat<const GlobalObject>(functions(), globals()); 386285cf9a8SReid Kleckner } 387285cf9a8SReid Kleckner 388285cf9a8SReid Kleckner iterator_range<Module::global_value_iterator> Module::global_values() { 389285cf9a8SReid Kleckner return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs()); 390285cf9a8SReid Kleckner } 391285cf9a8SReid Kleckner iterator_range<Module::const_global_value_iterator> 392285cf9a8SReid Kleckner Module::global_values() const { 393285cf9a8SReid Kleckner return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs()); 394285cf9a8SReid Kleckner } 395285cf9a8SReid Kleckner 396ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 397ef860a24SChandler Carruth // Methods to control the materialization of GlobalValues in the Module. 398ef860a24SChandler Carruth // 399ef860a24SChandler Carruth void Module::setMaterializer(GVMaterializer *GVM) { 400ef860a24SChandler Carruth assert(!Materializer && 401c4a03483SRafael Espindola "Module already has a GVMaterializer. Call materializeAll" 402ef860a24SChandler Carruth " to clear it out before setting another one."); 403ef860a24SChandler Carruth Materializer.reset(GVM); 404ef860a24SChandler Carruth } 405ef860a24SChandler Carruth 4067f00d0a1SPeter Collingbourne Error Module::materialize(GlobalValue *GV) { 4072b11ad4fSRafael Espindola if (!Materializer) 4087f00d0a1SPeter Collingbourne return Error::success(); 4092b11ad4fSRafael Espindola 4105a52e6dcSRafael Espindola return Materializer->materialize(GV); 411ef860a24SChandler Carruth } 412ef860a24SChandler Carruth 4137f00d0a1SPeter Collingbourne Error Module::materializeAll() { 414ef860a24SChandler Carruth if (!Materializer) 4157f00d0a1SPeter Collingbourne return Error::success(); 416257a3536SRafael Espindola std::unique_ptr<GVMaterializer> M = std::move(Materializer); 417257a3536SRafael Espindola return M->materializeModule(); 418ef860a24SChandler Carruth } 419ef860a24SChandler Carruth 4207f00d0a1SPeter Collingbourne Error Module::materializeMetadata() { 421cba833a0SRafael Espindola if (!Materializer) 4227f00d0a1SPeter Collingbourne return Error::success(); 423cba833a0SRafael Espindola return Materializer->materializeMetadata(); 424cba833a0SRafael Espindola } 425cba833a0SRafael Espindola 426ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 427ef860a24SChandler Carruth // Other module related stuff. 428ef860a24SChandler Carruth // 429ef860a24SChandler Carruth 4302fa1e43aSRafael Espindola std::vector<StructType *> Module::getIdentifiedStructTypes() const { 4312fa1e43aSRafael Espindola // If we have a materializer, it is possible that some unread function 4322fa1e43aSRafael Espindola // uses a type that is currently not visible to a TypeFinder, so ask 4332fa1e43aSRafael Espindola // the materializer which types it created. 4342fa1e43aSRafael Espindola if (Materializer) 4352fa1e43aSRafael Espindola return Materializer->getIdentifiedStructTypes(); 4362fa1e43aSRafael Espindola 4372fa1e43aSRafael Espindola std::vector<StructType *> Ret; 4382fa1e43aSRafael Espindola TypeFinder SrcStructTypes; 4392fa1e43aSRafael Espindola SrcStructTypes.run(*this, true); 4402fa1e43aSRafael Espindola Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end()); 4412fa1e43aSRafael Espindola return Ret; 4422fa1e43aSRafael Espindola } 443ef860a24SChandler Carruth 444ef860a24SChandler Carruth // dropAllReferences() - This function causes all the subelements to "let go" 445ef860a24SChandler Carruth // of all references that they are maintaining. This allows one to 'delete' a 446ef860a24SChandler Carruth // whole module at a time, even though there may be circular references... first 447ef860a24SChandler Carruth // all references are dropped, and all use counts go to zero. Then everything 448ef860a24SChandler Carruth // is deleted for real. Note that no operations are valid on an object that 449ef860a24SChandler Carruth // has "dropped all references", except operator delete. 450ef860a24SChandler Carruth // 451ef860a24SChandler Carruth void Module::dropAllReferences() { 4523374910fSDavid Majnemer for (Function &F : *this) 4533374910fSDavid Majnemer F.dropAllReferences(); 454ef860a24SChandler Carruth 4553374910fSDavid Majnemer for (GlobalVariable &GV : globals()) 4563374910fSDavid Majnemer GV.dropAllReferences(); 457ef860a24SChandler Carruth 4583374910fSDavid Majnemer for (GlobalAlias &GA : aliases()) 4593374910fSDavid Majnemer GA.dropAllReferences(); 460a1feff70SDmitry Polukhin 461a1feff70SDmitry Polukhin for (GlobalIFunc &GIF : ifuncs()) 462a1feff70SDmitry Polukhin GIF.dropAllReferences(); 463ef860a24SChandler Carruth } 4640915c047SDiego Novillo 465ac6081cbSNirav Dave unsigned Module::getNumberRegisterParameters() const { 466ac6081cbSNirav Dave auto *Val = 467ac6081cbSNirav Dave cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters")); 468ac6081cbSNirav Dave if (!Val) 469ac6081cbSNirav Dave return 0; 470ac6081cbSNirav Dave return cast<ConstantInt>(Val->getValue())->getZExtValue(); 471ac6081cbSNirav Dave } 472ac6081cbSNirav Dave 4730915c047SDiego Novillo unsigned Module::getDwarfVersion() const { 4745bf8fef5SDuncan P. N. Exon Smith auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version")); 4750915c047SDiego Novillo if (!Val) 47612d2c120SReid Kleckner return 0; 47712d2c120SReid Kleckner return cast<ConstantInt>(Val->getValue())->getZExtValue(); 47812d2c120SReid Kleckner } 47912d2c120SReid Kleckner 48012d2c120SReid Kleckner unsigned Module::getCodeViewFlag() const { 48112d2c120SReid Kleckner auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView")); 48212d2c120SReid Kleckner if (!Val) 48312d2c120SReid Kleckner return 0; 4845bf8fef5SDuncan P. N. Exon Smith return cast<ConstantInt>(Val->getValue())->getZExtValue(); 4850915c047SDiego Novillo } 486dad0a645SDavid Majnemer 487e49374d0SJessica Paquette unsigned Module::getInstructionCount() { 488e49374d0SJessica Paquette unsigned NumInstrs = 0; 489e49374d0SJessica Paquette for (Function &F : FunctionList) 490e49374d0SJessica Paquette NumInstrs += F.getInstructionCount(); 491e49374d0SJessica Paquette return NumInstrs; 492e49374d0SJessica Paquette } 493e49374d0SJessica Paquette 494dad0a645SDavid Majnemer Comdat *Module::getOrInsertComdat(StringRef Name) { 4955106ce78SDavid Blaikie auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first; 496dad0a645SDavid Majnemer Entry.second.Name = &Entry; 497dad0a645SDavid Majnemer return &Entry.second; 498dad0a645SDavid Majnemer } 499771c132eSJustin Hibbits 500771c132eSJustin Hibbits PICLevel::Level Module::getPICLevel() const { 5015bf8fef5SDuncan P. N. Exon Smith auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level")); 502771c132eSJustin Hibbits 503083ca9bbSHans Wennborg if (!Val) 5044cccc488SDavide Italiano return PICLevel::NotPIC; 505771c132eSJustin Hibbits 5065bf8fef5SDuncan P. N. Exon Smith return static_cast<PICLevel::Level>( 5075bf8fef5SDuncan P. N. Exon Smith cast<ConstantInt>(Val->getValue())->getZExtValue()); 508771c132eSJustin Hibbits } 509771c132eSJustin Hibbits 510771c132eSJustin Hibbits void Module::setPICLevel(PICLevel::Level PL) { 5112db1369cSTeresa Johnson addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL); 512771c132eSJustin Hibbits } 513ecb05e51SEaswaran Raman 51446d47b8cSSriraman Tallam PIELevel::Level Module::getPIELevel() const { 51546d47b8cSSriraman Tallam auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level")); 51646d47b8cSSriraman Tallam 51746d47b8cSSriraman Tallam if (!Val) 51846d47b8cSSriraman Tallam return PIELevel::Default; 51946d47b8cSSriraman Tallam 52046d47b8cSSriraman Tallam return static_cast<PIELevel::Level>( 52146d47b8cSSriraman Tallam cast<ConstantInt>(Val->getValue())->getZExtValue()); 52246d47b8cSSriraman Tallam } 52346d47b8cSSriraman Tallam 52446d47b8cSSriraman Tallam void Module::setPIELevel(PIELevel::Level PL) { 5252db1369cSTeresa Johnson addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL); 52646d47b8cSSriraman Tallam } 52746d47b8cSSriraman Tallam 5283dea3f9eSCaroline Tice Optional<CodeModel::Model> Module::getCodeModel() const { 5293dea3f9eSCaroline Tice auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model")); 5303dea3f9eSCaroline Tice 5313dea3f9eSCaroline Tice if (!Val) 5323dea3f9eSCaroline Tice return None; 5333dea3f9eSCaroline Tice 5343dea3f9eSCaroline Tice return static_cast<CodeModel::Model>( 5353dea3f9eSCaroline Tice cast<ConstantInt>(Val->getValue())->getZExtValue()); 5363dea3f9eSCaroline Tice } 5373dea3f9eSCaroline Tice 5383dea3f9eSCaroline Tice void Module::setCodeModel(CodeModel::Model CL) { 5393dea3f9eSCaroline Tice // Linking object files with different code models is undefined behavior 5403dea3f9eSCaroline Tice // because the compiler would have to generate additional code (to span 5413dea3f9eSCaroline Tice // longer jumps) if a larger code model is used with a smaller one. 5423dea3f9eSCaroline Tice // Therefore we will treat attempts to mix code models as an error. 5433dea3f9eSCaroline Tice addModuleFlag(ModFlagBehavior::Error, "Code Model", CL); 5443dea3f9eSCaroline Tice } 5453dea3f9eSCaroline Tice 546a6ff69f6SRong Xu void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) { 547a6ff69f6SRong Xu if (Kind == ProfileSummary::PSK_CSInstr) 548a6ff69f6SRong Xu addModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M); 549a6ff69f6SRong Xu else 55026628d30SEaswaran Raman addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M); 55126628d30SEaswaran Raman } 55226628d30SEaswaran Raman 553a6ff69f6SRong Xu Metadata *Module::getProfileSummary(bool IsCS) { 554a6ff69f6SRong Xu return (IsCS ? getModuleFlag("CSProfileSummary") 555a6ff69f6SRong Xu : getModuleFlag("ProfileSummary")); 55626628d30SEaswaran Raman } 557b35cc691STeresa Johnson 558e2dcf7c3SPeter Collingbourne void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) { 559e2dcf7c3SPeter Collingbourne OwnedMemoryBuffer = std::move(MB); 560e2dcf7c3SPeter Collingbourne } 561e2dcf7c3SPeter Collingbourne 562609f8c01SSriraman Tallam bool Module::getRtLibUseGOT() const { 563609f8c01SSriraman Tallam auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT")); 564609f8c01SSriraman Tallam return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0); 565609f8c01SSriraman Tallam } 566609f8c01SSriraman Tallam 567609f8c01SSriraman Tallam void Module::setRtLibUseGOT() { 568609f8c01SSriraman Tallam addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1); 569609f8c01SSriraman Tallam } 570609f8c01SSriraman Tallam 571afa75d78SAlex Lorenz void Module::setSDKVersion(const VersionTuple &V) { 572afa75d78SAlex Lorenz SmallVector<unsigned, 3> Entries; 573afa75d78SAlex Lorenz Entries.push_back(V.getMajor()); 574afa75d78SAlex Lorenz if (auto Minor = V.getMinor()) { 575afa75d78SAlex Lorenz Entries.push_back(*Minor); 576afa75d78SAlex Lorenz if (auto Subminor = V.getSubminor()) 577afa75d78SAlex Lorenz Entries.push_back(*Subminor); 578afa75d78SAlex Lorenz // Ignore the 'build' component as it can't be represented in the object 579afa75d78SAlex Lorenz // file. 580afa75d78SAlex Lorenz } 581afa75d78SAlex Lorenz addModuleFlag(ModFlagBehavior::Warning, "SDK Version", 582afa75d78SAlex Lorenz ConstantDataArray::get(Context, Entries)); 583afa75d78SAlex Lorenz } 584afa75d78SAlex Lorenz 585afa75d78SAlex Lorenz VersionTuple Module::getSDKVersion() const { 586afa75d78SAlex Lorenz auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version")); 587afa75d78SAlex Lorenz if (!CM) 588afa75d78SAlex Lorenz return {}; 589afa75d78SAlex Lorenz auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue()); 590afa75d78SAlex Lorenz if (!Arr) 591afa75d78SAlex Lorenz return {}; 592afa75d78SAlex Lorenz auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> { 593afa75d78SAlex Lorenz if (Index >= Arr->getNumElements()) 594afa75d78SAlex Lorenz return None; 595afa75d78SAlex Lorenz return (unsigned)Arr->getElementAsInteger(Index); 596afa75d78SAlex Lorenz }; 597afa75d78SAlex Lorenz auto Major = getVersionComponent(0); 598afa75d78SAlex Lorenz if (!Major) 599afa75d78SAlex Lorenz return {}; 600afa75d78SAlex Lorenz VersionTuple Result = VersionTuple(*Major); 601afa75d78SAlex Lorenz if (auto Minor = getVersionComponent(1)) { 602afa75d78SAlex Lorenz Result = VersionTuple(*Major, *Minor); 603afa75d78SAlex Lorenz if (auto Subminor = getVersionComponent(2)) { 604afa75d78SAlex Lorenz Result = VersionTuple(*Major, *Minor, *Subminor); 605afa75d78SAlex Lorenz } 606afa75d78SAlex Lorenz } 607afa75d78SAlex Lorenz return Result; 608afa75d78SAlex Lorenz } 609afa75d78SAlex Lorenz 610b35cc691STeresa Johnson GlobalVariable *llvm::collectUsedGlobalVariables( 611b35cc691STeresa Johnson const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) { 612b35cc691STeresa Johnson const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used"; 613b35cc691STeresa Johnson GlobalVariable *GV = M.getGlobalVariable(Name); 614b35cc691STeresa Johnson if (!GV || !GV->hasInitializer()) 615b35cc691STeresa Johnson return GV; 616b35cc691STeresa Johnson 617b35cc691STeresa Johnson const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 618b35cc691STeresa Johnson for (Value *Op : Init->operands()) { 6192452d703SPeter Collingbourne GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts()); 620b35cc691STeresa Johnson Set.insert(G); 621b35cc691STeresa Johnson } 622b35cc691STeresa Johnson return GV; 623b35cc691STeresa Johnson } 624