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) 74e1164de5STeresa Johnson : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") { 75ef860a24SChandler Carruth ValSymTab = new ValueSymbolTable(); 76ef860a24SChandler Carruth NamedMDSymTab = new StringMap<NamedMDNode *>(); 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 NamedMDList.clear(); 88ef860a24SChandler Carruth delete ValSymTab; 89ef860a24SChandler Carruth delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab); 90ef860a24SChandler Carruth } 91ef860a24SChandler Carruth 92e14625faSSerge Guelton std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const { 93e6acbdc4SJF Bastien SmallString<32> Salt(P->getPassName()); 94e6acbdc4SJF Bastien 95e6acbdc4SJF Bastien // This RNG is guaranteed to produce the same random stream only 96e6acbdc4SJF Bastien // when the Module ID and thus the input filename is the same. This 97e6acbdc4SJF Bastien // might be problematic if the input filename extension changes 98e6acbdc4SJF Bastien // (e.g. from .c to .bc or .ll). 99e6acbdc4SJF Bastien // 100e6acbdc4SJF Bastien // We could store this salt in NamedMetadata, but this would make 101e6acbdc4SJF Bastien // the parameter non-const. This would unfortunately make this 102e6acbdc4SJF Bastien // interface unusable by any Machine passes, since they only have a 103e6acbdc4SJF Bastien // const reference to their IR Module. Alternatively we can always 104e6acbdc4SJF Bastien // store salt metadata from the Module constructor. 105e6acbdc4SJF Bastien Salt += sys::path::filename(getModuleIdentifier()); 106e6acbdc4SJF Bastien 107ad9bbc20SSerge Guelton return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt)); 108e6acbdc4SJF Bastien } 109e6acbdc4SJF Bastien 110ef860a24SChandler Carruth /// getNamedValue - Return the first global value in the module with 111ef860a24SChandler Carruth /// the specified name, of arbitrary type. This method returns null 112ef860a24SChandler Carruth /// if a global with the specified name is not found. 113ef860a24SChandler Carruth GlobalValue *Module::getNamedValue(StringRef Name) const { 114ef860a24SChandler Carruth return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name)); 115ef860a24SChandler Carruth } 116ef860a24SChandler Carruth 117ef860a24SChandler Carruth /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 118ef860a24SChandler Carruth /// This ID is uniqued across modules in the current LLVMContext. 119ef860a24SChandler Carruth unsigned Module::getMDKindID(StringRef Name) const { 120ef860a24SChandler Carruth return Context.getMDKindID(Name); 121ef860a24SChandler Carruth } 122ef860a24SChandler Carruth 123ef860a24SChandler Carruth /// getMDKindNames - Populate client supplied SmallVector with the name for 124ef860a24SChandler Carruth /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 125ef860a24SChandler Carruth /// so it is filled in as an empty string. 126ef860a24SChandler Carruth void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 127ef860a24SChandler Carruth return Context.getMDKindNames(Result); 128ef860a24SChandler Carruth } 129ef860a24SChandler Carruth 1309303c246SSanjoy Das void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const { 1319303c246SSanjoy Das return Context.getOperandBundleTags(Result); 1329303c246SSanjoy Das } 133ef860a24SChandler Carruth 134ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 135ef860a24SChandler Carruth // Methods for easy access to the functions in the module. 136ef860a24SChandler Carruth // 137ef860a24SChandler Carruth 138ef860a24SChandler Carruth // getOrInsertFunction - Look up the specified function in the module symbol 139ef860a24SChandler Carruth // table. If it does not exist, add a prototype for the function and return 140ef860a24SChandler Carruth // it. This is nice because it allows most passes to get away with not handling 141ef860a24SChandler Carruth // the symbol table directly for this common task. 142ef860a24SChandler Carruth // 14313680223SJames Y Knight FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty, 144b518054bSReid Kleckner AttributeList AttributeList) { 145ef860a24SChandler Carruth // See if we have a definition for the specified function already. 146ef860a24SChandler Carruth GlobalValue *F = getNamedValue(Name); 147c620761cSCraig Topper if (!F) { 148ef860a24SChandler Carruth // Nope, add it 1496bcf2ba2SAlexander Richardson Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, 1506bcf2ba2SAlexander Richardson DL.getProgramAddressSpace(), Name); 151ef860a24SChandler Carruth if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 152ef860a24SChandler Carruth New->setAttributes(AttributeList); 153ef860a24SChandler Carruth FunctionList.push_back(New); 15413680223SJames Y Knight return {Ty, New}; // Return the new prototype. 155ef860a24SChandler Carruth } 156ef860a24SChandler Carruth 157ef860a24SChandler Carruth // If the function exists but has the wrong type, return a bitcast to the 158ef860a24SChandler Carruth // right type. 1596bcf2ba2SAlexander Richardson auto *PTy = PointerType::get(Ty, F->getAddressSpace()); 1606bcf2ba2SAlexander Richardson if (F->getType() != PTy) 16113680223SJames Y Knight return {Ty, ConstantExpr::getBitCast(F, PTy)}; 162ef860a24SChandler Carruth 163ef860a24SChandler Carruth // Otherwise, we just found the existing function or a prototype. 16413680223SJames Y Knight return {Ty, F}; 165ef860a24SChandler Carruth } 166ef860a24SChandler Carruth 16713680223SJames Y Knight FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) { 168b518054bSReid Kleckner return getOrInsertFunction(Name, Ty, AttributeList()); 169ef860a24SChandler Carruth } 170ef860a24SChandler Carruth 171ef860a24SChandler Carruth // getFunction - Look up the specified function in the module symbol table. 172ef860a24SChandler Carruth // If it does not exist, return null. 173ef860a24SChandler Carruth // 174ef860a24SChandler Carruth Function *Module::getFunction(StringRef Name) const { 175ef860a24SChandler Carruth return dyn_cast_or_null<Function>(getNamedValue(Name)); 176ef860a24SChandler Carruth } 177ef860a24SChandler Carruth 178ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 179ef860a24SChandler Carruth // Methods for easy access to the global variables in the module. 180ef860a24SChandler Carruth // 181ef860a24SChandler Carruth 182ef860a24SChandler Carruth /// getGlobalVariable - Look up the specified global variable in the module 183ef860a24SChandler Carruth /// symbol table. If it does not exist, return null. The type argument 184ef860a24SChandler Carruth /// should be the underlying type of the global, i.e., it should not have 185ef860a24SChandler Carruth /// the top-level PointerType, which represents the address of the global. 186ef860a24SChandler Carruth /// If AllowLocal is set to true, this function will return types that 187ef860a24SChandler Carruth /// have an local. By default, these types are not returned. 188ef860a24SChandler Carruth /// 1891dd20e65SCraig Topper GlobalVariable *Module::getGlobalVariable(StringRef Name, 1901dd20e65SCraig Topper bool AllowLocal) const { 191ef860a24SChandler Carruth if (GlobalVariable *Result = 192ef860a24SChandler Carruth dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 193ef860a24SChandler Carruth if (AllowLocal || !Result->hasLocalLinkage()) 194ef860a24SChandler Carruth return Result; 195c620761cSCraig Topper return nullptr; 196ef860a24SChandler Carruth } 197ef860a24SChandler Carruth 198ef860a24SChandler Carruth /// getOrInsertGlobal - Look up the specified global in the module symbol table. 199ef860a24SChandler Carruth /// 1. If it does not exist, add a declaration of the global and return it. 200ef860a24SChandler Carruth /// 2. Else, the global exists but has the wrong type: return the function 201ef860a24SChandler Carruth /// with a constantexpr cast to the right type. 2025200fdf0SMatt Arsenault /// 3. Finally, if the existing global is the correct declaration, return the 203ef860a24SChandler Carruth /// existing global. 2046bc98ad7SPhilip Pfaffe Constant *Module::getOrInsertGlobal( 2056bc98ad7SPhilip Pfaffe StringRef Name, Type *Ty, 2066bc98ad7SPhilip Pfaffe function_ref<GlobalVariable *()> CreateGlobalCallback) { 207ef860a24SChandler Carruth // See if we have a definition for the specified global already. 208ef860a24SChandler Carruth GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)); 2096bc98ad7SPhilip Pfaffe if (!GV) 2106bc98ad7SPhilip Pfaffe GV = CreateGlobalCallback(); 2116bc98ad7SPhilip Pfaffe assert(GV && "The CreateGlobalCallback is expected to create a global"); 212ef860a24SChandler Carruth 213ef860a24SChandler Carruth // If the variable exists but has the wrong type, return a bitcast to the 214ef860a24SChandler Carruth // right type. 21527e783e9SMatt Arsenault Type *GVTy = GV->getType(); 21627e783e9SMatt Arsenault PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace()); 217a90a340fSMatt Arsenault if (GVTy != PTy) 21827e783e9SMatt Arsenault return ConstantExpr::getBitCast(GV, PTy); 219ef860a24SChandler Carruth 220ef860a24SChandler Carruth // Otherwise, we just found the existing function or a prototype. 221ef860a24SChandler Carruth return GV; 222ef860a24SChandler Carruth } 223ef860a24SChandler Carruth 2246bc98ad7SPhilip Pfaffe // Overload to construct a global variable using its constructor's defaults. 2256bc98ad7SPhilip Pfaffe Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 2266bc98ad7SPhilip Pfaffe return getOrInsertGlobal(Name, Ty, [&] { 2276bc98ad7SPhilip Pfaffe return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 2286bc98ad7SPhilip Pfaffe nullptr, Name); 2296bc98ad7SPhilip Pfaffe }); 2306bc98ad7SPhilip Pfaffe } 2316bc98ad7SPhilip Pfaffe 232ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 233ef860a24SChandler Carruth // Methods for easy access to the global variables in the module. 234ef860a24SChandler Carruth // 235ef860a24SChandler Carruth 236ef860a24SChandler Carruth // getNamedAlias - Look up the specified global in the module symbol table. 237ef860a24SChandler Carruth // If it does not exist, return null. 238ef860a24SChandler Carruth // 239ef860a24SChandler Carruth GlobalAlias *Module::getNamedAlias(StringRef Name) const { 240ef860a24SChandler Carruth return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 241ef860a24SChandler Carruth } 242ef860a24SChandler Carruth 243a1feff70SDmitry Polukhin GlobalIFunc *Module::getNamedIFunc(StringRef Name) const { 244a1feff70SDmitry Polukhin return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name)); 245a1feff70SDmitry Polukhin } 246a1feff70SDmitry Polukhin 247ef860a24SChandler Carruth /// getNamedMetadata - Return the first NamedMDNode in the module with the 248ef860a24SChandler Carruth /// specified name. This method returns null if a NamedMDNode with the 249ef860a24SChandler Carruth /// specified name is not found. 250ef860a24SChandler Carruth NamedMDNode *Module::getNamedMetadata(const Twine &Name) const { 251ef860a24SChandler Carruth SmallString<256> NameData; 252ef860a24SChandler Carruth StringRef NameRef = Name.toStringRef(NameData); 253ef860a24SChandler Carruth return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef); 254ef860a24SChandler Carruth } 255ef860a24SChandler Carruth 256ef860a24SChandler Carruth /// getOrInsertNamedMetadata - Return the first named MDNode in the module 257ef860a24SChandler Carruth /// with the specified name. This method returns a new NamedMDNode if a 258ef860a24SChandler Carruth /// NamedMDNode with the specified name is not found. 259ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 260ef860a24SChandler Carruth NamedMDNode *&NMD = 261ef860a24SChandler Carruth (*static_cast<StringMap<NamedMDNode *> *>(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) { 273ef860a24SChandler Carruth static_cast<StringMap<NamedMDNode *> *>(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 288ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the module flags in the provided vector. 289ef860a24SChandler Carruth void Module:: 290ef860a24SChandler Carruth getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 291ef860a24SChandler Carruth const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 292ef860a24SChandler Carruth if (!ModFlags) return; 293ef860a24SChandler Carruth 294de36e804SDuncan P. N. Exon Smith for (const MDNode *Flag : ModFlags->operands()) { 295af023adbSAlexey Samsonov ModFlagBehavior MFB; 296af023adbSAlexey Samsonov if (Flag->getNumOperands() >= 3 && 297af023adbSAlexey Samsonov isValidModFlagBehavior(Flag->getOperand(0), MFB) && 298d7677e7aSDavid Majnemer dyn_cast_or_null<MDString>(Flag->getOperand(1))) { 2998b4306ceSManman Ren // Check the operands of the MDNode before accessing the operands. 3008b4306ceSManman Ren // The verifier will actually catch these failures. 301ef860a24SChandler Carruth MDString *Key = cast<MDString>(Flag->getOperand(1)); 3025bf8fef5SDuncan P. N. Exon Smith Metadata *Val = Flag->getOperand(2); 303af023adbSAlexey Samsonov Flags.push_back(ModuleFlagEntry(MFB, Key, Val)); 304ef860a24SChandler Carruth } 305ef860a24SChandler Carruth } 3068b4306ceSManman Ren } 307ef860a24SChandler Carruth 3088bfde891SManman Ren /// Return the corresponding value if Key appears in module flags, otherwise 3098bfde891SManman Ren /// return null. 3105bf8fef5SDuncan P. N. Exon Smith Metadata *Module::getModuleFlag(StringRef Key) const { 3118bfde891SManman Ren SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 3128bfde891SManman Ren getModuleFlagsMetadata(ModuleFlags); 3133ad5c962SBenjamin Kramer for (const ModuleFlagEntry &MFE : ModuleFlags) { 3148bfde891SManman Ren if (Key == MFE.Key->getString()) 3158bfde891SManman Ren return MFE.Val; 3168bfde891SManman Ren } 317c620761cSCraig Topper return nullptr; 3188bfde891SManman Ren } 3198bfde891SManman Ren 320ef860a24SChandler Carruth /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that 321ef860a24SChandler Carruth /// represents module-level flags. This method returns null if there are no 322ef860a24SChandler Carruth /// module-level flags. 323ef860a24SChandler Carruth NamedMDNode *Module::getModuleFlagsMetadata() const { 324ef860a24SChandler Carruth return getNamedMetadata("llvm.module.flags"); 325ef860a24SChandler Carruth } 326ef860a24SChandler Carruth 327ef860a24SChandler Carruth /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 328ef860a24SChandler Carruth /// represents module-level flags. If module-level flags aren't found, it 329ef860a24SChandler Carruth /// creates the named metadata that contains them. 330ef860a24SChandler Carruth NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 331ef860a24SChandler Carruth return getOrInsertNamedMetadata("llvm.module.flags"); 332ef860a24SChandler Carruth } 333ef860a24SChandler Carruth 334ef860a24SChandler Carruth /// addModuleFlag - Add a module-level flag to the module-level flags 335ef860a24SChandler Carruth /// metadata. It will create the module-level flags named metadata if it doesn't 336ef860a24SChandler Carruth /// already exist. 337ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 3385bf8fef5SDuncan P. N. Exon Smith Metadata *Val) { 339ef860a24SChandler Carruth Type *Int32Ty = Type::getInt32Ty(Context); 3405bf8fef5SDuncan P. N. Exon Smith Metadata *Ops[3] = { 3415bf8fef5SDuncan P. N. Exon Smith ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)), 3425bf8fef5SDuncan P. N. Exon Smith MDString::get(Context, Key), Val}; 343ef860a24SChandler Carruth getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 344ef860a24SChandler Carruth } 345ef860a24SChandler Carruth void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 3465bf8fef5SDuncan P. N. Exon Smith Constant *Val) { 3475bf8fef5SDuncan P. N. Exon Smith addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val)); 3485bf8fef5SDuncan P. N. Exon Smith } 3495bf8fef5SDuncan P. N. Exon Smith void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 350ef860a24SChandler Carruth uint32_t Val) { 351ef860a24SChandler Carruth Type *Int32Ty = Type::getInt32Ty(Context); 352ef860a24SChandler Carruth addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 353ef860a24SChandler Carruth } 354ef860a24SChandler Carruth void Module::addModuleFlag(MDNode *Node) { 355ef860a24SChandler Carruth assert(Node->getNumOperands() == 3 && 356ef860a24SChandler Carruth "Invalid number of operands for module flag!"); 3575bf8fef5SDuncan P. N. Exon Smith assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) && 358ef860a24SChandler Carruth isa<MDString>(Node->getOperand(1)) && 359ef860a24SChandler Carruth "Invalid operand types for module flag!"); 360ef860a24SChandler Carruth getOrInsertModuleFlagsMetadata()->addOperand(Node); 361ef860a24SChandler Carruth } 362ef860a24SChandler Carruth 363f863ee29SRafael Espindola void Module::setDataLayout(StringRef Desc) { 364248ac139SRafael Espindola DL.reset(Desc); 365f863ee29SRafael Espindola } 366f863ee29SRafael Espindola 36746a43556SMehdi Amini void Module::setDataLayout(const DataLayout &Other) { DL = Other; } 368f863ee29SRafael Espindola 36946a43556SMehdi Amini const DataLayout &Module::getDataLayout() const { return DL; } 370f863ee29SRafael Espindola 3715992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator*() const { 3725992a72bSAdrian Prantl return cast<DICompileUnit>(CUs->getOperand(Idx)); 3735992a72bSAdrian Prantl } 3745992a72bSAdrian Prantl DICompileUnit *Module::debug_compile_units_iterator::operator->() const { 3755992a72bSAdrian Prantl return cast<DICompileUnit>(CUs->getOperand(Idx)); 3765992a72bSAdrian Prantl } 3775992a72bSAdrian Prantl 3785992a72bSAdrian Prantl void Module::debug_compile_units_iterator::SkipNoDebugCUs() { 3795992a72bSAdrian Prantl while (CUs && (Idx < CUs->getNumOperands()) && 3805992a72bSAdrian Prantl ((*this)->getEmissionKind() == DICompileUnit::NoDebug)) 3815992a72bSAdrian Prantl ++Idx; 3825992a72bSAdrian Prantl } 3835992a72bSAdrian Prantl 384ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 385ef860a24SChandler Carruth // Methods to control the materialization of GlobalValues in the Module. 386ef860a24SChandler Carruth // 387ef860a24SChandler Carruth void Module::setMaterializer(GVMaterializer *GVM) { 388ef860a24SChandler Carruth assert(!Materializer && 389c4a03483SRafael Espindola "Module already has a GVMaterializer. Call materializeAll" 390ef860a24SChandler Carruth " to clear it out before setting another one."); 391ef860a24SChandler Carruth Materializer.reset(GVM); 392ef860a24SChandler Carruth } 393ef860a24SChandler Carruth 3947f00d0a1SPeter Collingbourne Error Module::materialize(GlobalValue *GV) { 3952b11ad4fSRafael Espindola if (!Materializer) 3967f00d0a1SPeter Collingbourne return Error::success(); 3972b11ad4fSRafael Espindola 3985a52e6dcSRafael Espindola return Materializer->materialize(GV); 399ef860a24SChandler Carruth } 400ef860a24SChandler Carruth 4017f00d0a1SPeter Collingbourne Error Module::materializeAll() { 402ef860a24SChandler Carruth if (!Materializer) 4037f00d0a1SPeter Collingbourne return Error::success(); 404257a3536SRafael Espindola std::unique_ptr<GVMaterializer> M = std::move(Materializer); 405257a3536SRafael Espindola return M->materializeModule(); 406ef860a24SChandler Carruth } 407ef860a24SChandler Carruth 4087f00d0a1SPeter Collingbourne Error Module::materializeMetadata() { 409cba833a0SRafael Espindola if (!Materializer) 4107f00d0a1SPeter Collingbourne return Error::success(); 411cba833a0SRafael Espindola return Materializer->materializeMetadata(); 412cba833a0SRafael Espindola } 413cba833a0SRafael Espindola 414ef860a24SChandler Carruth //===----------------------------------------------------------------------===// 415ef860a24SChandler Carruth // Other module related stuff. 416ef860a24SChandler Carruth // 417ef860a24SChandler Carruth 4182fa1e43aSRafael Espindola std::vector<StructType *> Module::getIdentifiedStructTypes() const { 4192fa1e43aSRafael Espindola // If we have a materializer, it is possible that some unread function 4202fa1e43aSRafael Espindola // uses a type that is currently not visible to a TypeFinder, so ask 4212fa1e43aSRafael Espindola // the materializer which types it created. 4222fa1e43aSRafael Espindola if (Materializer) 4232fa1e43aSRafael Espindola return Materializer->getIdentifiedStructTypes(); 4242fa1e43aSRafael Espindola 4252fa1e43aSRafael Espindola std::vector<StructType *> Ret; 4262fa1e43aSRafael Espindola TypeFinder SrcStructTypes; 4272fa1e43aSRafael Espindola SrcStructTypes.run(*this, true); 4282fa1e43aSRafael Espindola Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end()); 4292fa1e43aSRafael Espindola return Ret; 4302fa1e43aSRafael Espindola } 431ef860a24SChandler Carruth 432ef860a24SChandler Carruth // dropAllReferences() - This function causes all the subelements to "let go" 433ef860a24SChandler Carruth // of all references that they are maintaining. This allows one to 'delete' a 434ef860a24SChandler Carruth // whole module at a time, even though there may be circular references... first 435ef860a24SChandler Carruth // all references are dropped, and all use counts go to zero. Then everything 436ef860a24SChandler Carruth // is deleted for real. Note that no operations are valid on an object that 437ef860a24SChandler Carruth // has "dropped all references", except operator delete. 438ef860a24SChandler Carruth // 439ef860a24SChandler Carruth void Module::dropAllReferences() { 4403374910fSDavid Majnemer for (Function &F : *this) 4413374910fSDavid Majnemer F.dropAllReferences(); 442ef860a24SChandler Carruth 4433374910fSDavid Majnemer for (GlobalVariable &GV : globals()) 4443374910fSDavid Majnemer GV.dropAllReferences(); 445ef860a24SChandler Carruth 4463374910fSDavid Majnemer for (GlobalAlias &GA : aliases()) 4473374910fSDavid Majnemer GA.dropAllReferences(); 448a1feff70SDmitry Polukhin 449a1feff70SDmitry Polukhin for (GlobalIFunc &GIF : ifuncs()) 450a1feff70SDmitry Polukhin GIF.dropAllReferences(); 451ef860a24SChandler Carruth } 4520915c047SDiego Novillo 453ac6081cbSNirav Dave unsigned Module::getNumberRegisterParameters() const { 454ac6081cbSNirav Dave auto *Val = 455ac6081cbSNirav Dave cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters")); 456ac6081cbSNirav Dave if (!Val) 457ac6081cbSNirav Dave return 0; 458ac6081cbSNirav Dave return cast<ConstantInt>(Val->getValue())->getZExtValue(); 459ac6081cbSNirav Dave } 460ac6081cbSNirav Dave 4610915c047SDiego Novillo unsigned Module::getDwarfVersion() const { 4625bf8fef5SDuncan P. N. Exon Smith auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version")); 4630915c047SDiego Novillo if (!Val) 46412d2c120SReid Kleckner return 0; 46512d2c120SReid Kleckner return cast<ConstantInt>(Val->getValue())->getZExtValue(); 46612d2c120SReid Kleckner } 46712d2c120SReid Kleckner 46812d2c120SReid Kleckner unsigned Module::getCodeViewFlag() const { 46912d2c120SReid Kleckner auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView")); 47012d2c120SReid Kleckner if (!Val) 47112d2c120SReid Kleckner return 0; 4725bf8fef5SDuncan P. N. Exon Smith return cast<ConstantInt>(Val->getValue())->getZExtValue(); 4730915c047SDiego Novillo } 474dad0a645SDavid Majnemer 475e49374d0SJessica Paquette unsigned Module::getInstructionCount() { 476e49374d0SJessica Paquette unsigned NumInstrs = 0; 477e49374d0SJessica Paquette for (Function &F : FunctionList) 478e49374d0SJessica Paquette NumInstrs += F.getInstructionCount(); 479e49374d0SJessica Paquette return NumInstrs; 480e49374d0SJessica Paquette } 481e49374d0SJessica Paquette 482dad0a645SDavid Majnemer Comdat *Module::getOrInsertComdat(StringRef Name) { 4835106ce78SDavid Blaikie auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first; 484dad0a645SDavid Majnemer Entry.second.Name = &Entry; 485dad0a645SDavid Majnemer return &Entry.second; 486dad0a645SDavid Majnemer } 487771c132eSJustin Hibbits 488771c132eSJustin Hibbits PICLevel::Level Module::getPICLevel() const { 4895bf8fef5SDuncan P. N. Exon Smith auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level")); 490771c132eSJustin Hibbits 491083ca9bbSHans Wennborg if (!Val) 4924cccc488SDavide Italiano return PICLevel::NotPIC; 493771c132eSJustin Hibbits 4945bf8fef5SDuncan P. N. Exon Smith return static_cast<PICLevel::Level>( 4955bf8fef5SDuncan P. N. Exon Smith cast<ConstantInt>(Val->getValue())->getZExtValue()); 496771c132eSJustin Hibbits } 497771c132eSJustin Hibbits 498771c132eSJustin Hibbits void Module::setPICLevel(PICLevel::Level PL) { 4992db1369cSTeresa Johnson addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL); 500771c132eSJustin Hibbits } 501ecb05e51SEaswaran Raman 50246d47b8cSSriraman Tallam PIELevel::Level Module::getPIELevel() const { 50346d47b8cSSriraman Tallam auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level")); 50446d47b8cSSriraman Tallam 50546d47b8cSSriraman Tallam if (!Val) 50646d47b8cSSriraman Tallam return PIELevel::Default; 50746d47b8cSSriraman Tallam 50846d47b8cSSriraman Tallam return static_cast<PIELevel::Level>( 50946d47b8cSSriraman Tallam cast<ConstantInt>(Val->getValue())->getZExtValue()); 51046d47b8cSSriraman Tallam } 51146d47b8cSSriraman Tallam 51246d47b8cSSriraman Tallam void Module::setPIELevel(PIELevel::Level PL) { 5132db1369cSTeresa Johnson addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL); 51446d47b8cSSriraman Tallam } 51546d47b8cSSriraman Tallam 5163dea3f9eSCaroline Tice Optional<CodeModel::Model> Module::getCodeModel() const { 5173dea3f9eSCaroline Tice auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model")); 5183dea3f9eSCaroline Tice 5193dea3f9eSCaroline Tice if (!Val) 5203dea3f9eSCaroline Tice return None; 5213dea3f9eSCaroline Tice 5223dea3f9eSCaroline Tice return static_cast<CodeModel::Model>( 5233dea3f9eSCaroline Tice cast<ConstantInt>(Val->getValue())->getZExtValue()); 5243dea3f9eSCaroline Tice } 5253dea3f9eSCaroline Tice 5263dea3f9eSCaroline Tice void Module::setCodeModel(CodeModel::Model CL) { 5273dea3f9eSCaroline Tice // Linking object files with different code models is undefined behavior 5283dea3f9eSCaroline Tice // because the compiler would have to generate additional code (to span 5293dea3f9eSCaroline Tice // longer jumps) if a larger code model is used with a smaller one. 5303dea3f9eSCaroline Tice // Therefore we will treat attempts to mix code models as an error. 5313dea3f9eSCaroline Tice addModuleFlag(ModFlagBehavior::Error, "Code Model", CL); 5323dea3f9eSCaroline Tice } 5333dea3f9eSCaroline Tice 534a6ff69f6SRong Xu void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) { 535a6ff69f6SRong Xu if (Kind == ProfileSummary::PSK_CSInstr) 536a6ff69f6SRong Xu addModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M); 537a6ff69f6SRong Xu else 53826628d30SEaswaran Raman addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M); 53926628d30SEaswaran Raman } 54026628d30SEaswaran Raman 541a6ff69f6SRong Xu Metadata *Module::getProfileSummary(bool IsCS) { 542a6ff69f6SRong Xu return (IsCS ? getModuleFlag("CSProfileSummary") 543a6ff69f6SRong Xu : getModuleFlag("ProfileSummary")); 54426628d30SEaswaran Raman } 545b35cc691STeresa Johnson 546e2dcf7c3SPeter Collingbourne void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) { 547e2dcf7c3SPeter Collingbourne OwnedMemoryBuffer = std::move(MB); 548e2dcf7c3SPeter Collingbourne } 549e2dcf7c3SPeter Collingbourne 550609f8c01SSriraman Tallam bool Module::getRtLibUseGOT() const { 551609f8c01SSriraman Tallam auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT")); 552609f8c01SSriraman Tallam return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0); 553609f8c01SSriraman Tallam } 554609f8c01SSriraman Tallam 555609f8c01SSriraman Tallam void Module::setRtLibUseGOT() { 556609f8c01SSriraman Tallam addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1); 557609f8c01SSriraman Tallam } 558609f8c01SSriraman Tallam 559afa75d78SAlex Lorenz void Module::setSDKVersion(const VersionTuple &V) { 560afa75d78SAlex Lorenz SmallVector<unsigned, 3> Entries; 561afa75d78SAlex Lorenz Entries.push_back(V.getMajor()); 562afa75d78SAlex Lorenz if (auto Minor = V.getMinor()) { 563afa75d78SAlex Lorenz Entries.push_back(*Minor); 564afa75d78SAlex Lorenz if (auto Subminor = V.getSubminor()) 565afa75d78SAlex Lorenz Entries.push_back(*Subminor); 566afa75d78SAlex Lorenz // Ignore the 'build' component as it can't be represented in the object 567afa75d78SAlex Lorenz // file. 568afa75d78SAlex Lorenz } 569afa75d78SAlex Lorenz addModuleFlag(ModFlagBehavior::Warning, "SDK Version", 570afa75d78SAlex Lorenz ConstantDataArray::get(Context, Entries)); 571afa75d78SAlex Lorenz } 572afa75d78SAlex Lorenz 573afa75d78SAlex Lorenz VersionTuple Module::getSDKVersion() const { 574afa75d78SAlex Lorenz auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version")); 575afa75d78SAlex Lorenz if (!CM) 576afa75d78SAlex Lorenz return {}; 577afa75d78SAlex Lorenz auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue()); 578afa75d78SAlex Lorenz if (!Arr) 579afa75d78SAlex Lorenz return {}; 580afa75d78SAlex Lorenz auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> { 581afa75d78SAlex Lorenz if (Index >= Arr->getNumElements()) 582afa75d78SAlex Lorenz return None; 583afa75d78SAlex Lorenz return (unsigned)Arr->getElementAsInteger(Index); 584afa75d78SAlex Lorenz }; 585afa75d78SAlex Lorenz auto Major = getVersionComponent(0); 586afa75d78SAlex Lorenz if (!Major) 587afa75d78SAlex Lorenz return {}; 588afa75d78SAlex Lorenz VersionTuple Result = VersionTuple(*Major); 589afa75d78SAlex Lorenz if (auto Minor = getVersionComponent(1)) { 590afa75d78SAlex Lorenz Result = VersionTuple(*Major, *Minor); 591afa75d78SAlex Lorenz if (auto Subminor = getVersionComponent(2)) { 592afa75d78SAlex Lorenz Result = VersionTuple(*Major, *Minor, *Subminor); 593afa75d78SAlex Lorenz } 594afa75d78SAlex Lorenz } 595afa75d78SAlex Lorenz return Result; 596afa75d78SAlex Lorenz } 597afa75d78SAlex Lorenz 598b35cc691STeresa Johnson GlobalVariable *llvm::collectUsedGlobalVariables( 599b35cc691STeresa Johnson const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) { 600b35cc691STeresa Johnson const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used"; 601b35cc691STeresa Johnson GlobalVariable *GV = M.getGlobalVariable(Name); 602b35cc691STeresa Johnson if (!GV || !GV->hasInitializer()) 603b35cc691STeresa Johnson return GV; 604b35cc691STeresa Johnson 605b35cc691STeresa Johnson const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 606b35cc691STeresa Johnson for (Value *Op : Init->operands()) { 607*2452d703SPeter Collingbourne GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts()); 608b35cc691STeresa Johnson Set.insert(G); 609b35cc691STeresa Johnson } 610b35cc691STeresa Johnson return GV; 611b35cc691STeresa Johnson } 612