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) 74*46ed9331SDavid Blaikie : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>()), 75*46ed9331SDavid Blaikie Materializer(), ModuleID(MID), SourceFileName(MID), DL("") { 76ef860a24SChandler Carruth Context.addModule(this); 77ef860a24SChandler Carruth } 78ef860a24SChandler Carruth 79ef860a24SChandler Carruth Module::~Module() { 80ef860a24SChandler Carruth Context.removeModule(this); 81ef860a24SChandler Carruth dropAllReferences(); 82ef860a24SChandler Carruth GlobalList.clear(); 83ef860a24SChandler Carruth FunctionList.clear(); 84ef860a24SChandler Carruth AliasList.clear(); 85a1feff70SDmitry Polukhin IFuncList.clear(); 86ef860a24SChandler Carruth } 87ef860a24SChandler Carruth 88e14625faSSerge Guelton std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const { 89e6acbdc4SJF Bastien SmallString<32> Salt(P->getPassName()); 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 103ad9bbc20SSerge Guelton return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt)); 104e6acbdc4SJF Bastien } 105e6acbdc4SJF Bastien 106ef860a24SChandler Carruth /// getNamedValue - Return the first global value in the module with 107ef860a24SChandler Carruth /// the specified name, of arbitrary type. This method returns null 108ef860a24SChandler Carruth /// if a global with the specified name is not found. 109ef860a24SChandler Carruth GlobalValue *Module::getNamedValue(StringRef Name) const { 110ef860a24SChandler Carruth return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name)); 111ef860a24SChandler Carruth } 112ef860a24SChandler Carruth 113ef860a24SChandler Carruth /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 114ef860a24SChandler Carruth /// This ID is uniqued across modules in the current LLVMContext. 115ef860a24SChandler Carruth unsigned Module::getMDKindID(StringRef Name) const { 116ef860a24SChandler Carruth return Context.getMDKindID(Name); 117ef860a24SChandler Carruth } 118ef860a24SChandler Carruth 119ef860a24SChandler Carruth /// getMDKindNames - Populate client supplied SmallVector with the name for 120ef860a24SChandler Carruth /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 121ef860a24SChandler Carruth /// so it is filled in as an empty string. 122ef860a24SChandler Carruth void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 123ef860a24SChandler Carruth return Context.getMDKindNames(Result); 124ef860a24SChandler Carruth } 125ef860a24SChandler Carruth 1269303c246SSanjoy Das void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const { 1279303c246SSanjoy Das return Context.getOperandBundleTags(Result); 1289303c246SSanjoy Das } 129ef860a24SChandler Carruth 130ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 131ef860a24SChandler Carruth // Methods for easy access to the functions in the module. 132ef860a24SChandler Carruth // 133ef860a24SChandler Carruth 134ef860a24SChandler Carruth // getOrInsertFunction - Look up the specified function in the module symbol 135ef860a24SChandler Carruth // table. If it does not exist, add a prototype for the function and return 136ef860a24SChandler Carruth // it. This is nice because it allows most passes to get away with not handling 137ef860a24SChandler Carruth // the symbol table directly for this common task. 138ef860a24SChandler Carruth // 13913680223SJames Y Knight FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty, 140b518054bSReid Kleckner AttributeList AttributeList) { 141ef860a24SChandler Carruth // See if we have a definition for the specified function already. 142ef860a24SChandler Carruth GlobalValue *F = getNamedValue(Name); 143c620761cSCraig Topper if (!F) { 144ef860a24SChandler Carruth // Nope, add it 1456bcf2ba2SAlexander Richardson Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, 1466bcf2ba2SAlexander Richardson DL.getProgramAddressSpace(), Name); 147ef860a24SChandler Carruth if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 148ef860a24SChandler Carruth New->setAttributes(AttributeList); 149ef860a24SChandler Carruth FunctionList.push_back(New); 15013680223SJames Y Knight return {Ty, New}; // Return the new prototype. 151ef860a24SChandler Carruth } 152ef860a24SChandler Carruth 153ef860a24SChandler Carruth // If the function exists but has the wrong type, return a bitcast to the 154ef860a24SChandler Carruth // right type. 1556bcf2ba2SAlexander Richardson auto *PTy = PointerType::get(Ty, F->getAddressSpace()); 1566bcf2ba2SAlexander Richardson if (F->getType() != PTy) 15713680223SJames Y Knight return {Ty, ConstantExpr::getBitCast(F, PTy)}; 158ef860a24SChandler Carruth 159ef860a24SChandler Carruth // Otherwise, we just found the existing function or a prototype. 16013680223SJames Y Knight return {Ty, F}; 161ef860a24SChandler Carruth } 162ef860a24SChandler Carruth 16313680223SJames Y Knight FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) { 164b518054bSReid Kleckner return getOrInsertFunction(Name, Ty, AttributeList()); 165ef860a24SChandler Carruth } 166ef860a24SChandler Carruth 167ef860a24SChandler Carruth // getFunction - Look up the specified function in the module symbol table. 168ef860a24SChandler Carruth // If it does not exist, return null. 169ef860a24SChandler Carruth // 170ef860a24SChandler Carruth Function *Module::getFunction(StringRef Name) const { 171ef860a24SChandler Carruth return dyn_cast_or_null<Function>(getNamedValue(Name)); 172ef860a24SChandler Carruth } 173ef860a24SChandler Carruth 174ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 175ef860a24SChandler Carruth // Methods for easy access to the global variables in the module. 176ef860a24SChandler Carruth // 177ef860a24SChandler Carruth 178ef860a24SChandler Carruth /// getGlobalVariable - Look up the specified global variable in the module 179ef860a24SChandler Carruth /// symbol table. If it does not exist, return null. The type argument 180ef860a24SChandler Carruth /// should be the underlying type of the global, i.e., it should not have 181ef860a24SChandler Carruth /// the top-level PointerType, which represents the address of the global. 182ef860a24SChandler Carruth /// If AllowLocal is set to true, this function will return types that 183ef860a24SChandler Carruth /// have an local. By default, these types are not returned. 184ef860a24SChandler Carruth /// 1851dd20e65SCraig Topper GlobalVariable *Module::getGlobalVariable(StringRef Name, 1861dd20e65SCraig Topper bool AllowLocal) const { 187ef860a24SChandler Carruth if (GlobalVariable *Result = 188ef860a24SChandler Carruth dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 189ef860a24SChandler Carruth if (AllowLocal || !Result->hasLocalLinkage()) 190ef860a24SChandler Carruth return Result; 191c620761cSCraig Topper return nullptr; 192ef860a24SChandler Carruth } 193ef860a24SChandler Carruth 194ef860a24SChandler Carruth /// getOrInsertGlobal - Look up the specified global in the module symbol table. 195ef860a24SChandler Carruth /// 1. If it does not exist, add a declaration of the global and return it. 196ef860a24SChandler Carruth /// 2. Else, the global exists but has the wrong type: return the function 197ef860a24SChandler Carruth /// with a constantexpr cast to the right type. 1985200fdf0SMatt Arsenault /// 3. Finally, if the existing global is the correct declaration, return the 199ef860a24SChandler Carruth /// existing global. 2006bc98ad7SPhilip Pfaffe Constant *Module::getOrInsertGlobal( 2016bc98ad7SPhilip Pfaffe StringRef Name, Type *Ty, 2026bc98ad7SPhilip Pfaffe function_ref<GlobalVariable *()> CreateGlobalCallback) { 203ef860a24SChandler Carruth // See if we have a definition for the specified global already. 204ef860a24SChandler Carruth GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)); 2056bc98ad7SPhilip Pfaffe if (!GV) 2066bc98ad7SPhilip Pfaffe GV = CreateGlobalCallback(); 2076bc98ad7SPhilip Pfaffe assert(GV && "The CreateGlobalCallback is expected to create a global"); 208ef860a24SChandler Carruth 209ef860a24SChandler Carruth // If the variable exists but has the wrong type, return a bitcast to the 210ef860a24SChandler Carruth // right type. 21127e783e9SMatt Arsenault Type *GVTy = GV->getType(); 21227e783e9SMatt Arsenault PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace()); 213a90a340fSMatt Arsenault if (GVTy != PTy) 21427e783e9SMatt Arsenault return ConstantExpr::getBitCast(GV, PTy); 215ef860a24SChandler Carruth 216ef860a24SChandler Carruth // Otherwise, we just found the existing function or a prototype. 217ef860a24SChandler Carruth return GV; 218ef860a24SChandler Carruth } 219ef860a24SChandler Carruth 2206bc98ad7SPhilip Pfaffe // Overload to construct a global variable using its constructor's defaults. 2216bc98ad7SPhilip Pfaffe Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 2226bc98ad7SPhilip Pfaffe return getOrInsertGlobal(Name, Ty, [&] { 2236bc98ad7SPhilip Pfaffe return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 2246bc98ad7SPhilip Pfaffe nullptr, Name); 2256bc98ad7SPhilip Pfaffe }); 2266bc98ad7SPhilip Pfaffe } 2276bc98ad7SPhilip Pfaffe 228ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 229ef860a24SChandler Carruth // Methods for easy access to the global variables in the module. 230ef860a24SChandler Carruth // 231ef860a24SChandler Carruth 232ef860a24SChandler Carruth // getNamedAlias - Look up the specified global in the module symbol table. 233ef860a24SChandler Carruth // If it does not exist, return null. 234ef860a24SChandler Carruth // 235ef860a24SChandler Carruth GlobalAlias *Module::getNamedAlias(StringRef Name) const { 236ef860a24SChandler Carruth return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 237ef860a24SChandler Carruth } 238ef860a24SChandler Carruth 239a1feff70SDmitry Polukhin GlobalIFunc *Module::getNamedIFunc(StringRef Name) const { 240a1feff70SDmitry Polukhin return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name)); 241a1feff70SDmitry Polukhin } 242a1feff70SDmitry Polukhin 243ef860a24SChandler Carruth /// getNamedMetadata - Return the first NamedMDNode in the module with the 244ef860a24SChandler Carruth /// specified name. This method returns null if a NamedMDNode with the 245ef860a24SChandler Carruth /// specified name is not found. 246ef860a24SChandler Carruth NamedMDNode *Module::getNamedMetadata(const Twine &Name) const { 247ef860a24SChandler Carruth SmallString<256> NameData; 248ef860a24SChandler Carruth StringRef NameRef = Name.toStringRef(NameData); 249daab9227SBrian Gesiak return NamedMDSymTab.lookup(NameRef); 250ef860a24SChandler Carruth } 251ef860a24SChandler Carruth 252ef860a24SChandler Carruth /// getOrInsertNamedMetadata - Return the first named MDNode in the module 253ef860a24SChandler Carruth /// with the specified name. This method returns a new NamedMDNode if a 254ef860a24SChandler Carruth /// NamedMDNode with the specified name is not found. 255ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 256daab9227SBrian Gesiak NamedMDNode *&NMD = NamedMDSymTab[Name]; 257ef860a24SChandler Carruth if (!NMD) { 258ef860a24SChandler Carruth NMD = new NamedMDNode(Name); 259ef860a24SChandler Carruth NMD->setParent(this); 260ef860a24SChandler Carruth NamedMDList.push_back(NMD); 261ef860a24SChandler Carruth } 262ef860a24SChandler Carruth return NMD; 263ef860a24SChandler Carruth } 264ef860a24SChandler Carruth 265ef860a24SChandler Carruth /// eraseNamedMetadata - Remove the given NamedMDNode from this module and 266ef860a24SChandler Carruth /// delete it. 267ef860a24SChandler Carruth void Module::eraseNamedMetadata(NamedMDNode *NMD) { 268daab9227SBrian Gesiak NamedMDSymTab.erase(NMD->getName()); 26952888a67SDuncan P. N. Exon Smith NamedMDList.erase(NMD->getIterator()); 270ef860a24SChandler Carruth } 271ef860a24SChandler Carruth 2725bf8fef5SDuncan P. N. Exon Smith bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) { 273d7677e7aSDavid Majnemer if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) { 274af023adbSAlexey Samsonov uint64_t Val = Behavior->getLimitedValue(); 275af023adbSAlexey Samsonov if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) { 276af023adbSAlexey Samsonov MFB = static_cast<ModFlagBehavior>(Val); 277af023adbSAlexey Samsonov return true; 278af023adbSAlexey Samsonov } 279af023adbSAlexey Samsonov } 280af023adbSAlexey Samsonov return false; 281af023adbSAlexey Samsonov } 282af023adbSAlexey Samsonov 283ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the module flags in the provided vector. 284ef860a24SChandler Carruth void Module:: 285ef860a24SChandler Carruth getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 286ef860a24SChandler Carruth const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 287ef860a24SChandler Carruth if (!ModFlags) return; 288ef860a24SChandler Carruth 289de36e804SDuncan P. N. Exon Smith for (const MDNode *Flag : ModFlags->operands()) { 290af023adbSAlexey Samsonov ModFlagBehavior MFB; 291af023adbSAlexey Samsonov if (Flag->getNumOperands() >= 3 && 292af023adbSAlexey Samsonov isValidModFlagBehavior(Flag->getOperand(0), MFB) && 293d7677e7aSDavid Majnemer dyn_cast_or_null<MDString>(Flag->getOperand(1))) { 2948b4306ceSManman Ren // Check the operands of the MDNode before accessing the operands. 2958b4306ceSManman Ren // The verifier will actually catch these failures. 296ef860a24SChandler Carruth MDString *Key = cast<MDString>(Flag->getOperand(1)); 2975bf8fef5SDuncan P. N. Exon Smith Metadata *Val = Flag->getOperand(2); 298af023adbSAlexey Samsonov Flags.push_back(ModuleFlagEntry(MFB, Key, Val)); 299ef860a24SChandler Carruth } 300ef860a24SChandler Carruth } 3018b4306ceSManman Ren } 302ef860a24SChandler Carruth 3038bfde891SManman Ren /// Return the corresponding value if Key appears in module flags, otherwise 3048bfde891SManman Ren /// return null. 3055bf8fef5SDuncan P. N. Exon Smith Metadata *Module::getModuleFlag(StringRef Key) const { 3068bfde891SManman Ren SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 3078bfde891SManman Ren getModuleFlagsMetadata(ModuleFlags); 3083ad5c962SBenjamin Kramer for (const ModuleFlagEntry &MFE : ModuleFlags) { 3098bfde891SManman Ren if (Key == MFE.Key->getString()) 3108bfde891SManman Ren return MFE.Val; 3118bfde891SManman Ren } 312c620761cSCraig Topper return nullptr; 3138bfde891SManman Ren } 3148bfde891SManman Ren 315ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that 316ef860a24SChandler Carruth /// represents module-level flags. This method returns null if there are no 317ef860a24SChandler Carruth /// module-level flags. 318ef860a24SChandler Carruth NamedMDNode *Module::getModuleFlagsMetadata() const { 319ef860a24SChandler Carruth return getNamedMetadata("llvm.module.flags"); 320ef860a24SChandler Carruth } 321ef860a24SChandler Carruth 322ef860a24SChandler Carruth /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 323ef860a24SChandler Carruth /// represents module-level flags. If module-level flags aren't found, it 324ef860a24SChandler Carruth /// creates the named metadata that contains them. 325ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 326ef860a24SChandler Carruth return getOrInsertNamedMetadata("llvm.module.flags"); 327ef860a24SChandler Carruth } 328ef860a24SChandler Carruth 329ef860a24SChandler Carruth /// addModuleFlag - Add a module-level flag to the module-level flags 330ef860a24SChandler Carruth /// metadata. It will create the module-level flags named metadata if it doesn't 331ef860a24SChandler Carruth /// already exist. 332ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 3335bf8fef5SDuncan P. N. Exon Smith Metadata *Val) { 334ef860a24SChandler Carruth Type *Int32Ty = Type::getInt32Ty(Context); 3355bf8fef5SDuncan P. N. Exon Smith Metadata *Ops[3] = { 3365bf8fef5SDuncan P. N. Exon Smith ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)), 3375bf8fef5SDuncan P. N. Exon Smith MDString::get(Context, Key), Val}; 338ef860a24SChandler Carruth getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 339ef860a24SChandler Carruth } 340ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 3415bf8fef5SDuncan P. N. Exon Smith Constant *Val) { 3425bf8fef5SDuncan P. N. Exon Smith addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val)); 3435bf8fef5SDuncan P. N. Exon Smith } 3445bf8fef5SDuncan P. N. Exon Smith void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 345ef860a24SChandler Carruth uint32_t Val) { 346ef860a24SChandler Carruth Type *Int32Ty = Type::getInt32Ty(Context); 347ef860a24SChandler Carruth addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 348ef860a24SChandler Carruth } 349ef860a24SChandler Carruth void Module::addModuleFlag(MDNode *Node) { 350ef860a24SChandler Carruth assert(Node->getNumOperands() == 3 && 351ef860a24SChandler Carruth "Invalid number of operands for module flag!"); 3525bf8fef5SDuncan P. N. Exon Smith assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) && 353ef860a24SChandler Carruth isa<MDString>(Node->getOperand(1)) && 354ef860a24SChandler Carruth "Invalid operand types for module flag!"); 355ef860a24SChandler Carruth getOrInsertModuleFlagsMetadata()->addOperand(Node); 356ef860a24SChandler Carruth } 357ef860a24SChandler Carruth 358f863ee29SRafael Espindola void Module::setDataLayout(StringRef Desc) { 359248ac139SRafael Espindola DL.reset(Desc); 360f863ee29SRafael Espindola } 361f863ee29SRafael Espindola 36246a43556SMehdi Amini void Module::setDataLayout(const DataLayout &Other) { DL = Other; } 363f863ee29SRafael Espindola 36446a43556SMehdi Amini const DataLayout &Module::getDataLayout() const { return DL; } 365f863ee29SRafael Espindola 3665992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator*() const { 3675992a72bSAdrian Prantl return cast<DICompileUnit>(CUs->getOperand(Idx)); 3685992a72bSAdrian Prantl } 3695992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator->() const { 3705992a72bSAdrian Prantl return cast<DICompileUnit>(CUs->getOperand(Idx)); 3715992a72bSAdrian Prantl } 3725992a72bSAdrian Prantl 3735992a72bSAdrian Prantl void Module::debug_compile_units_iterator::SkipNoDebugCUs() { 3745992a72bSAdrian Prantl while (CUs && (Idx < CUs->getNumOperands()) && 3755992a72bSAdrian Prantl ((*this)->getEmissionKind() == DICompileUnit::NoDebug)) 3765992a72bSAdrian Prantl ++Idx; 3775992a72bSAdrian Prantl } 3785992a72bSAdrian Prantl 379285cf9a8SReid Kleckner iterator_range<Module::global_object_iterator> Module::global_objects() { 380285cf9a8SReid Kleckner return concat<GlobalObject>(functions(), globals()); 381285cf9a8SReid Kleckner } 382285cf9a8SReid Kleckner iterator_range<Module::const_global_object_iterator> 383285cf9a8SReid Kleckner Module::global_objects() const { 384285cf9a8SReid Kleckner return concat<const GlobalObject>(functions(), globals()); 385285cf9a8SReid Kleckner } 386285cf9a8SReid Kleckner 387285cf9a8SReid Kleckner iterator_range<Module::global_value_iterator> Module::global_values() { 388285cf9a8SReid Kleckner return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs()); 389285cf9a8SReid Kleckner } 390285cf9a8SReid Kleckner iterator_range<Module::const_global_value_iterator> 391285cf9a8SReid Kleckner Module::global_values() const { 392285cf9a8SReid Kleckner return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs()); 393285cf9a8SReid Kleckner } 394285cf9a8SReid Kleckner 395ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 396ef860a24SChandler Carruth // Methods to control the materialization of GlobalValues in the Module. 397ef860a24SChandler Carruth // 398ef860a24SChandler Carruth void Module::setMaterializer(GVMaterializer *GVM) { 399ef860a24SChandler Carruth assert(!Materializer && 400c4a03483SRafael Espindola "Module already has a GVMaterializer. Call materializeAll" 401ef860a24SChandler Carruth " to clear it out before setting another one."); 402ef860a24SChandler Carruth Materializer.reset(GVM); 403ef860a24SChandler Carruth } 404ef860a24SChandler Carruth 4057f00d0a1SPeter Collingbourne Error Module::materialize(GlobalValue *GV) { 4062b11ad4fSRafael Espindola if (!Materializer) 4077f00d0a1SPeter Collingbourne return Error::success(); 4082b11ad4fSRafael Espindola 4095a52e6dcSRafael Espindola return Materializer->materialize(GV); 410ef860a24SChandler Carruth } 411ef860a24SChandler Carruth 4127f00d0a1SPeter Collingbourne Error Module::materializeAll() { 413ef860a24SChandler Carruth if (!Materializer) 4147f00d0a1SPeter Collingbourne return Error::success(); 415257a3536SRafael Espindola std::unique_ptr<GVMaterializer> M = std::move(Materializer); 416257a3536SRafael Espindola return M->materializeModule(); 417ef860a24SChandler Carruth } 418ef860a24SChandler Carruth 4197f00d0a1SPeter Collingbourne Error Module::materializeMetadata() { 420cba833a0SRafael Espindola if (!Materializer) 4217f00d0a1SPeter Collingbourne return Error::success(); 422cba833a0SRafael Espindola return Materializer->materializeMetadata(); 423cba833a0SRafael Espindola } 424cba833a0SRafael Espindola 425ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 426ef860a24SChandler Carruth // Other module related stuff. 427ef860a24SChandler Carruth // 428ef860a24SChandler Carruth 4292fa1e43aSRafael Espindola std::vector<StructType *> Module::getIdentifiedStructTypes() const { 4302fa1e43aSRafael Espindola // If we have a materializer, it is possible that some unread function 4312fa1e43aSRafael Espindola // uses a type that is currently not visible to a TypeFinder, so ask 4322fa1e43aSRafael Espindola // the materializer which types it created. 4332fa1e43aSRafael Espindola if (Materializer) 4342fa1e43aSRafael Espindola return Materializer->getIdentifiedStructTypes(); 4352fa1e43aSRafael Espindola 4362fa1e43aSRafael Espindola std::vector<StructType *> Ret; 4372fa1e43aSRafael Espindola TypeFinder SrcStructTypes; 4382fa1e43aSRafael Espindola SrcStructTypes.run(*this, true); 4392fa1e43aSRafael Espindola Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end()); 4402fa1e43aSRafael Espindola return Ret; 4412fa1e43aSRafael Espindola } 442ef860a24SChandler Carruth 443ef860a24SChandler Carruth // dropAllReferences() - This function causes all the subelements to "let go" 444ef860a24SChandler Carruth // of all references that they are maintaining. This allows one to 'delete' a 445ef860a24SChandler Carruth // whole module at a time, even though there may be circular references... first 446ef860a24SChandler Carruth // all references are dropped, and all use counts go to zero. Then everything 447ef860a24SChandler Carruth // is deleted for real. Note that no operations are valid on an object that 448ef860a24SChandler Carruth // has "dropped all references", except operator delete. 449ef860a24SChandler Carruth // 450ef860a24SChandler Carruth void Module::dropAllReferences() { 4513374910fSDavid Majnemer for (Function &F : *this) 4523374910fSDavid Majnemer F.dropAllReferences(); 453ef860a24SChandler Carruth 4543374910fSDavid Majnemer for (GlobalVariable &GV : globals()) 4553374910fSDavid Majnemer GV.dropAllReferences(); 456ef860a24SChandler Carruth 4573374910fSDavid Majnemer for (GlobalAlias &GA : aliases()) 4583374910fSDavid Majnemer GA.dropAllReferences(); 459a1feff70SDmitry Polukhin 460a1feff70SDmitry Polukhin for (GlobalIFunc &GIF : ifuncs()) 461a1feff70SDmitry Polukhin GIF.dropAllReferences(); 462ef860a24SChandler Carruth } 4630915c047SDiego Novillo 464ac6081cbSNirav Dave unsigned Module::getNumberRegisterParameters() const { 465ac6081cbSNirav Dave auto *Val = 466ac6081cbSNirav Dave cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters")); 467ac6081cbSNirav Dave if (!Val) 468ac6081cbSNirav Dave return 0; 469ac6081cbSNirav Dave return cast<ConstantInt>(Val->getValue())->getZExtValue(); 470ac6081cbSNirav Dave } 471ac6081cbSNirav Dave 4720915c047SDiego Novillo unsigned Module::getDwarfVersion() const { 4735bf8fef5SDuncan P. N. Exon Smith auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version")); 4740915c047SDiego Novillo if (!Val) 47512d2c120SReid Kleckner return 0; 47612d2c120SReid Kleckner return cast<ConstantInt>(Val->getValue())->getZExtValue(); 47712d2c120SReid Kleckner } 47812d2c120SReid Kleckner 47912d2c120SReid Kleckner unsigned Module::getCodeViewFlag() const { 48012d2c120SReid Kleckner auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView")); 48112d2c120SReid Kleckner if (!Val) 48212d2c120SReid Kleckner return 0; 4835bf8fef5SDuncan P. N. Exon Smith return cast<ConstantInt>(Val->getValue())->getZExtValue(); 4840915c047SDiego Novillo } 485dad0a645SDavid Majnemer 486e49374d0SJessica Paquette unsigned Module::getInstructionCount() { 487e49374d0SJessica Paquette unsigned NumInstrs = 0; 488e49374d0SJessica Paquette for (Function &F : FunctionList) 489e49374d0SJessica Paquette NumInstrs += F.getInstructionCount(); 490e49374d0SJessica Paquette return NumInstrs; 491e49374d0SJessica Paquette } 492e49374d0SJessica Paquette 493dad0a645SDavid Majnemer Comdat *Module::getOrInsertComdat(StringRef Name) { 4945106ce78SDavid Blaikie auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first; 495dad0a645SDavid Majnemer Entry.second.Name = &Entry; 496dad0a645SDavid Majnemer return &Entry.second; 497dad0a645SDavid Majnemer } 498771c132eSJustin Hibbits 499771c132eSJustin Hibbits PICLevel::Level Module::getPICLevel() const { 5005bf8fef5SDuncan P. N. Exon Smith auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level")); 501771c132eSJustin Hibbits 502083ca9bbSHans Wennborg if (!Val) 5034cccc488SDavide Italiano return PICLevel::NotPIC; 504771c132eSJustin Hibbits 5055bf8fef5SDuncan P. N. Exon Smith return static_cast<PICLevel::Level>( 5065bf8fef5SDuncan P. N. Exon Smith cast<ConstantInt>(Val->getValue())->getZExtValue()); 507771c132eSJustin Hibbits } 508771c132eSJustin Hibbits 509771c132eSJustin Hibbits void Module::setPICLevel(PICLevel::Level PL) { 5102db1369cSTeresa Johnson addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL); 511771c132eSJustin Hibbits } 512ecb05e51SEaswaran Raman 51346d47b8cSSriraman Tallam PIELevel::Level Module::getPIELevel() const { 51446d47b8cSSriraman Tallam auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level")); 51546d47b8cSSriraman Tallam 51646d47b8cSSriraman Tallam if (!Val) 51746d47b8cSSriraman Tallam return PIELevel::Default; 51846d47b8cSSriraman Tallam 51946d47b8cSSriraman Tallam return static_cast<PIELevel::Level>( 52046d47b8cSSriraman Tallam cast<ConstantInt>(Val->getValue())->getZExtValue()); 52146d47b8cSSriraman Tallam } 52246d47b8cSSriraman Tallam 52346d47b8cSSriraman Tallam void Module::setPIELevel(PIELevel::Level PL) { 5242db1369cSTeresa Johnson addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL); 52546d47b8cSSriraman Tallam } 52646d47b8cSSriraman Tallam 5273dea3f9eSCaroline Tice Optional<CodeModel::Model> Module::getCodeModel() const { 5283dea3f9eSCaroline Tice auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model")); 5293dea3f9eSCaroline Tice 5303dea3f9eSCaroline Tice if (!Val) 5313dea3f9eSCaroline Tice return None; 5323dea3f9eSCaroline Tice 5333dea3f9eSCaroline Tice return static_cast<CodeModel::Model>( 5343dea3f9eSCaroline Tice cast<ConstantInt>(Val->getValue())->getZExtValue()); 5353dea3f9eSCaroline Tice } 5363dea3f9eSCaroline Tice 5373dea3f9eSCaroline Tice void Module::setCodeModel(CodeModel::Model CL) { 5383dea3f9eSCaroline Tice // Linking object files with different code models is undefined behavior 5393dea3f9eSCaroline Tice // because the compiler would have to generate additional code (to span 5403dea3f9eSCaroline Tice // longer jumps) if a larger code model is used with a smaller one. 5413dea3f9eSCaroline Tice // Therefore we will treat attempts to mix code models as an error. 5423dea3f9eSCaroline Tice addModuleFlag(ModFlagBehavior::Error, "Code Model", CL); 5433dea3f9eSCaroline Tice } 5443dea3f9eSCaroline Tice 545a6ff69f6SRong Xu void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) { 546a6ff69f6SRong Xu if (Kind == ProfileSummary::PSK_CSInstr) 547a6ff69f6SRong Xu addModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M); 548a6ff69f6SRong Xu else 54926628d30SEaswaran Raman addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M); 55026628d30SEaswaran Raman } 55126628d30SEaswaran Raman 552a6ff69f6SRong Xu Metadata *Module::getProfileSummary(bool IsCS) { 553a6ff69f6SRong Xu return (IsCS ? getModuleFlag("CSProfileSummary") 554a6ff69f6SRong Xu : getModuleFlag("ProfileSummary")); 55526628d30SEaswaran Raman } 556b35cc691STeresa Johnson 557e2dcf7c3SPeter Collingbourne void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) { 558e2dcf7c3SPeter Collingbourne OwnedMemoryBuffer = std::move(MB); 559e2dcf7c3SPeter Collingbourne } 560e2dcf7c3SPeter Collingbourne 561609f8c01SSriraman Tallam bool Module::getRtLibUseGOT() const { 562609f8c01SSriraman Tallam auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT")); 563609f8c01SSriraman Tallam return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0); 564609f8c01SSriraman Tallam } 565609f8c01SSriraman Tallam 566609f8c01SSriraman Tallam void Module::setRtLibUseGOT() { 567609f8c01SSriraman Tallam addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1); 568609f8c01SSriraman Tallam } 569609f8c01SSriraman Tallam 570afa75d78SAlex Lorenz void Module::setSDKVersion(const VersionTuple &V) { 571afa75d78SAlex Lorenz SmallVector<unsigned, 3> Entries; 572afa75d78SAlex Lorenz Entries.push_back(V.getMajor()); 573afa75d78SAlex Lorenz if (auto Minor = V.getMinor()) { 574afa75d78SAlex Lorenz Entries.push_back(*Minor); 575afa75d78SAlex Lorenz if (auto Subminor = V.getSubminor()) 576afa75d78SAlex Lorenz Entries.push_back(*Subminor); 577afa75d78SAlex Lorenz // Ignore the 'build' component as it can't be represented in the object 578afa75d78SAlex Lorenz // file. 579afa75d78SAlex Lorenz } 580afa75d78SAlex Lorenz addModuleFlag(ModFlagBehavior::Warning, "SDK Version", 581afa75d78SAlex Lorenz ConstantDataArray::get(Context, Entries)); 582afa75d78SAlex Lorenz } 583afa75d78SAlex Lorenz 584afa75d78SAlex Lorenz VersionTuple Module::getSDKVersion() const { 585afa75d78SAlex Lorenz auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version")); 586afa75d78SAlex Lorenz if (!CM) 587afa75d78SAlex Lorenz return {}; 588afa75d78SAlex Lorenz auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue()); 589afa75d78SAlex Lorenz if (!Arr) 590afa75d78SAlex Lorenz return {}; 591afa75d78SAlex Lorenz auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> { 592afa75d78SAlex Lorenz if (Index >= Arr->getNumElements()) 593afa75d78SAlex Lorenz return None; 594afa75d78SAlex Lorenz return (unsigned)Arr->getElementAsInteger(Index); 595afa75d78SAlex Lorenz }; 596afa75d78SAlex Lorenz auto Major = getVersionComponent(0); 597afa75d78SAlex Lorenz if (!Major) 598afa75d78SAlex Lorenz return {}; 599afa75d78SAlex Lorenz VersionTuple Result = VersionTuple(*Major); 600afa75d78SAlex Lorenz if (auto Minor = getVersionComponent(1)) { 601afa75d78SAlex Lorenz Result = VersionTuple(*Major, *Minor); 602afa75d78SAlex Lorenz if (auto Subminor = getVersionComponent(2)) { 603afa75d78SAlex Lorenz Result = VersionTuple(*Major, *Minor, *Subminor); 604afa75d78SAlex Lorenz } 605afa75d78SAlex Lorenz } 606afa75d78SAlex Lorenz return Result; 607afa75d78SAlex Lorenz } 608afa75d78SAlex Lorenz 609b35cc691STeresa Johnson GlobalVariable *llvm::collectUsedGlobalVariables( 610b35cc691STeresa Johnson const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) { 611b35cc691STeresa Johnson const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used"; 612b35cc691STeresa Johnson GlobalVariable *GV = M.getGlobalVariable(Name); 613b35cc691STeresa Johnson if (!GV || !GV->hasInitializer()) 614b35cc691STeresa Johnson return GV; 615b35cc691STeresa Johnson 616b35cc691STeresa Johnson const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 617b35cc691STeresa Johnson for (Value *Op : Init->operands()) { 6182452d703SPeter Collingbourne GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts()); 619b35cc691STeresa Johnson Set.insert(G); 620b35cc691STeresa Johnson } 621b35cc691STeresa Johnson return GV; 622b35cc691STeresa Johnson } 623