Home | History | Annotate | Download | only in IR
      1 //===-- Module.cpp - Implement the Module class ---------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the Module class for the IR library.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "llvm/IR/Module.h"
     15 #include "SymbolTableListTraitsImpl.h"
     16 #include "llvm/ADT/STLExtras.h"
     17 #include "llvm/ADT/SmallPtrSet.h"
     18 #include "llvm/ADT/SmallString.h"
     19 #include "llvm/ADT/StringExtras.h"
     20 #include "llvm/IR/Constants.h"
     21 #include "llvm/IR/DerivedTypes.h"
     22 #include "llvm/IR/DebugInfoMetadata.h"
     23 #include "llvm/IR/GVMaterializer.h"
     24 #include "llvm/IR/InstrTypes.h"
     25 #include "llvm/IR/LLVMContext.h"
     26 #include "llvm/IR/TypeFinder.h"
     27 #include "llvm/Support/Dwarf.h"
     28 #include "llvm/Support/Path.h"
     29 #include "llvm/Support/RandomNumberGenerator.h"
     30 #include <algorithm>
     31 #include <cstdarg>
     32 #include <cstdlib>
     33 
     34 using namespace llvm;
     35 
     36 //===----------------------------------------------------------------------===//
     37 // Methods to implement the globals and functions lists.
     38 //
     39 
     40 // Explicit instantiations of SymbolTableListTraits since some of the methods
     41 // are not in the public header file.
     42 template class llvm::SymbolTableListTraits<Function>;
     43 template class llvm::SymbolTableListTraits<GlobalVariable>;
     44 template class llvm::SymbolTableListTraits<GlobalAlias>;
     45 template class llvm::SymbolTableListTraits<GlobalIFunc>;
     46 
     47 //===----------------------------------------------------------------------===//
     48 // Primitive Module methods.
     49 //
     50 
     51 Module::Module(StringRef MID, LLVMContext &C)
     52     : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
     53   ValSymTab = new ValueSymbolTable();
     54   NamedMDSymTab = new StringMap<NamedMDNode *>();
     55   Context.addModule(this);
     56 }
     57 
     58 Module::~Module() {
     59   Context.removeModule(this);
     60   dropAllReferences();
     61   GlobalList.clear();
     62   FunctionList.clear();
     63   AliasList.clear();
     64   IFuncList.clear();
     65   NamedMDList.clear();
     66   delete ValSymTab;
     67   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
     68 }
     69 
     70 RandomNumberGenerator *Module::createRNG(const Pass* P) const {
     71   SmallString<32> Salt(P->getPassName());
     72 
     73   // This RNG is guaranteed to produce the same random stream only
     74   // when the Module ID and thus the input filename is the same. This
     75   // might be problematic if the input filename extension changes
     76   // (e.g. from .c to .bc or .ll).
     77   //
     78   // We could store this salt in NamedMetadata, but this would make
     79   // the parameter non-const. This would unfortunately make this
     80   // interface unusable by any Machine passes, since they only have a
     81   // const reference to their IR Module. Alternatively we can always
     82   // store salt metadata from the Module constructor.
     83   Salt += sys::path::filename(getModuleIdentifier());
     84 
     85   return new RandomNumberGenerator(Salt);
     86 }
     87 
     88 /// getNamedValue - Return the first global value in the module with
     89 /// the specified name, of arbitrary type.  This method returns null
     90 /// if a global with the specified name is not found.
     91 GlobalValue *Module::getNamedValue(StringRef Name) const {
     92   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
     93 }
     94 
     95 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
     96 /// This ID is uniqued across modules in the current LLVMContext.
     97 unsigned Module::getMDKindID(StringRef Name) const {
     98   return Context.getMDKindID(Name);
     99 }
    100 
    101 /// getMDKindNames - Populate client supplied SmallVector with the name for
    102 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
    103 /// so it is filled in as an empty string.
    104 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
    105   return Context.getMDKindNames(Result);
    106 }
    107 
    108 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
    109   return Context.getOperandBundleTags(Result);
    110 }
    111 
    112 //===----------------------------------------------------------------------===//
    113 // Methods for easy access to the functions in the module.
    114 //
    115 
    116 // getOrInsertFunction - Look up the specified function in the module symbol
    117 // table.  If it does not exist, add a prototype for the function and return
    118 // it.  This is nice because it allows most passes to get away with not handling
    119 // the symbol table directly for this common task.
    120 //
    121 Constant *Module::getOrInsertFunction(StringRef Name,
    122                                       FunctionType *Ty,
    123                                       AttributeSet AttributeList) {
    124   // See if we have a definition for the specified function already.
    125   GlobalValue *F = getNamedValue(Name);
    126   if (!F) {
    127     // Nope, add it
    128     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
    129     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
    130       New->setAttributes(AttributeList);
    131     FunctionList.push_back(New);
    132     return New;                    // Return the new prototype.
    133   }
    134 
    135   // If the function exists but has the wrong type, return a bitcast to the
    136   // right type.
    137   if (F->getType() != PointerType::getUnqual(Ty))
    138     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
    139 
    140   // Otherwise, we just found the existing function or a prototype.
    141   return F;
    142 }
    143 
    144 Constant *Module::getOrInsertFunction(StringRef Name,
    145                                       FunctionType *Ty) {
    146   return getOrInsertFunction(Name, Ty, AttributeSet());
    147 }
    148 
    149 // getOrInsertFunction - Look up the specified function in the module symbol
    150 // table.  If it does not exist, add a prototype for the function and return it.
    151 // This version of the method takes a null terminated list of function
    152 // arguments, which makes it easier for clients to use.
    153 //
    154 Constant *Module::getOrInsertFunction(StringRef Name,
    155                                       AttributeSet AttributeList,
    156                                       Type *RetTy, ...) {
    157   va_list Args;
    158   va_start(Args, RetTy);
    159 
    160   // Build the list of argument types...
    161   std::vector<Type*> ArgTys;
    162   while (Type *ArgTy = va_arg(Args, Type*))
    163     ArgTys.push_back(ArgTy);
    164 
    165   va_end(Args);
    166 
    167   // Build the function type and chain to the other getOrInsertFunction...
    168   return getOrInsertFunction(Name,
    169                              FunctionType::get(RetTy, ArgTys, false),
    170                              AttributeList);
    171 }
    172 
    173 Constant *Module::getOrInsertFunction(StringRef Name,
    174                                       Type *RetTy, ...) {
    175   va_list Args;
    176   va_start(Args, RetTy);
    177 
    178   // Build the list of argument types...
    179   std::vector<Type*> ArgTys;
    180   while (Type *ArgTy = va_arg(Args, Type*))
    181     ArgTys.push_back(ArgTy);
    182 
    183   va_end(Args);
    184 
    185   // Build the function type and chain to the other getOrInsertFunction...
    186   return getOrInsertFunction(Name,
    187                              FunctionType::get(RetTy, ArgTys, false),
    188                              AttributeSet());
    189 }
    190 
    191 // getFunction - Look up the specified function in the module symbol table.
    192 // If it does not exist, return null.
    193 //
    194 Function *Module::getFunction(StringRef Name) const {
    195   return dyn_cast_or_null<Function>(getNamedValue(Name));
    196 }
    197 
    198 //===----------------------------------------------------------------------===//
    199 // Methods for easy access to the global variables in the module.
    200 //
    201 
    202 /// getGlobalVariable - Look up the specified global variable in the module
    203 /// symbol table.  If it does not exist, return null.  The type argument
    204 /// should be the underlying type of the global, i.e., it should not have
    205 /// the top-level PointerType, which represents the address of the global.
    206 /// If AllowLocal is set to true, this function will return types that
    207 /// have an local. By default, these types are not returned.
    208 ///
    209 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
    210   if (GlobalVariable *Result =
    211       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
    212     if (AllowLocal || !Result->hasLocalLinkage())
    213       return Result;
    214   return nullptr;
    215 }
    216 
    217 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
    218 ///   1. If it does not exist, add a declaration of the global and return it.
    219 ///   2. Else, the global exists but has the wrong type: return the function
    220 ///      with a constantexpr cast to the right type.
    221 ///   3. Finally, if the existing global is the correct declaration, return the
    222 ///      existing global.
    223 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
    224   // See if we have a definition for the specified global already.
    225   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
    226   if (!GV) {
    227     // Nope, add it
    228     GlobalVariable *New =
    229       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
    230                          nullptr, Name);
    231      return New;                    // Return the new declaration.
    232   }
    233 
    234   // If the variable exists but has the wrong type, return a bitcast to the
    235   // right type.
    236   Type *GVTy = GV->getType();
    237   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
    238   if (GVTy != PTy)
    239     return ConstantExpr::getBitCast(GV, PTy);
    240 
    241   // Otherwise, we just found the existing function or a prototype.
    242   return GV;
    243 }
    244 
    245 //===----------------------------------------------------------------------===//
    246 // Methods for easy access to the global variables in the module.
    247 //
    248 
    249 // getNamedAlias - Look up the specified global in the module symbol table.
    250 // If it does not exist, return null.
    251 //
    252 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
    253   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
    254 }
    255 
    256 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
    257   return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
    258 }
    259 
    260 /// getNamedMetadata - Return the first NamedMDNode in the module with the
    261 /// specified name. This method returns null if a NamedMDNode with the
    262 /// specified name is not found.
    263 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
    264   SmallString<256> NameData;
    265   StringRef NameRef = Name.toStringRef(NameData);
    266   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
    267 }
    268 
    269 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
    270 /// with the specified name. This method returns a new NamedMDNode if a
    271 /// NamedMDNode with the specified name is not found.
    272 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
    273   NamedMDNode *&NMD =
    274     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
    275   if (!NMD) {
    276     NMD = new NamedMDNode(Name);
    277     NMD->setParent(this);
    278     NamedMDList.push_back(NMD);
    279   }
    280   return NMD;
    281 }
    282 
    283 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
    284 /// delete it.
    285 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
    286   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
    287   NamedMDList.erase(NMD->getIterator());
    288 }
    289 
    290 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
    291   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
    292     uint64_t Val = Behavior->getLimitedValue();
    293     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
    294       MFB = static_cast<ModFlagBehavior>(Val);
    295       return true;
    296     }
    297   }
    298   return false;
    299 }
    300 
    301 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
    302 void Module::
    303 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
    304   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
    305   if (!ModFlags) return;
    306 
    307   for (const MDNode *Flag : ModFlags->operands()) {
    308     ModFlagBehavior MFB;
    309     if (Flag->getNumOperands() >= 3 &&
    310         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
    311         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
    312       // Check the operands of the MDNode before accessing the operands.
    313       // The verifier will actually catch these failures.
    314       MDString *Key = cast<MDString>(Flag->getOperand(1));
    315       Metadata *Val = Flag->getOperand(2);
    316       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
    317     }
    318   }
    319 }
    320 
    321 /// Return the corresponding value if Key appears in module flags, otherwise
    322 /// return null.
    323 Metadata *Module::getModuleFlag(StringRef Key) const {
    324   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
    325   getModuleFlagsMetadata(ModuleFlags);
    326   for (const ModuleFlagEntry &MFE : ModuleFlags) {
    327     if (Key == MFE.Key->getString())
    328       return MFE.Val;
    329   }
    330   return nullptr;
    331 }
    332 
    333 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
    334 /// represents module-level flags. This method returns null if there are no
    335 /// module-level flags.
    336 NamedMDNode *Module::getModuleFlagsMetadata() const {
    337   return getNamedMetadata("llvm.module.flags");
    338 }
    339 
    340 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
    341 /// represents module-level flags. If module-level flags aren't found, it
    342 /// creates the named metadata that contains them.
    343 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
    344   return getOrInsertNamedMetadata("llvm.module.flags");
    345 }
    346 
    347 /// addModuleFlag - Add a module-level flag to the module-level flags
    348 /// metadata. It will create the module-level flags named metadata if it doesn't
    349 /// already exist.
    350 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
    351                            Metadata *Val) {
    352   Type *Int32Ty = Type::getInt32Ty(Context);
    353   Metadata *Ops[3] = {
    354       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
    355       MDString::get(Context, Key), Val};
    356   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
    357 }
    358 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
    359                            Constant *Val) {
    360   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
    361 }
    362 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
    363                            uint32_t Val) {
    364   Type *Int32Ty = Type::getInt32Ty(Context);
    365   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
    366 }
    367 void Module::addModuleFlag(MDNode *Node) {
    368   assert(Node->getNumOperands() == 3 &&
    369          "Invalid number of operands for module flag!");
    370   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
    371          isa<MDString>(Node->getOperand(1)) &&
    372          "Invalid operand types for module flag!");
    373   getOrInsertModuleFlagsMetadata()->addOperand(Node);
    374 }
    375 
    376 void Module::setDataLayout(StringRef Desc) {
    377   DL.reset(Desc);
    378 }
    379 
    380 void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
    381 
    382 const DataLayout &Module::getDataLayout() const { return DL; }
    383 
    384 DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
    385   return cast<DICompileUnit>(CUs->getOperand(Idx));
    386 }
    387 DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
    388   return cast<DICompileUnit>(CUs->getOperand(Idx));
    389 }
    390 
    391 void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
    392   while (CUs && (Idx < CUs->getNumOperands()) &&
    393          ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
    394     ++Idx;
    395 }
    396 
    397 //===----------------------------------------------------------------------===//
    398 // Methods to control the materialization of GlobalValues in the Module.
    399 //
    400 void Module::setMaterializer(GVMaterializer *GVM) {
    401   assert(!Materializer &&
    402          "Module already has a GVMaterializer.  Call materializeAll"
    403          " to clear it out before setting another one.");
    404   Materializer.reset(GVM);
    405 }
    406 
    407 std::error_code Module::materialize(GlobalValue *GV) {
    408   if (!Materializer)
    409     return std::error_code();
    410 
    411   return Materializer->materialize(GV);
    412 }
    413 
    414 std::error_code Module::materializeAll() {
    415   if (!Materializer)
    416     return std::error_code();
    417   std::unique_ptr<GVMaterializer> M = std::move(Materializer);
    418   return M->materializeModule();
    419 }
    420 
    421 std::error_code Module::materializeMetadata() {
    422   if (!Materializer)
    423     return std::error_code();
    424   return Materializer->materializeMetadata();
    425 }
    426 
    427 //===----------------------------------------------------------------------===//
    428 // Other module related stuff.
    429 //
    430 
    431 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
    432   // If we have a materializer, it is possible that some unread function
    433   // uses a type that is currently not visible to a TypeFinder, so ask
    434   // the materializer which types it created.
    435   if (Materializer)
    436     return Materializer->getIdentifiedStructTypes();
    437 
    438   std::vector<StructType *> Ret;
    439   TypeFinder SrcStructTypes;
    440   SrcStructTypes.run(*this, true);
    441   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
    442   return Ret;
    443 }
    444 
    445 // dropAllReferences() - This function causes all the subelements to "let go"
    446 // of all references that they are maintaining.  This allows one to 'delete' a
    447 // whole module at a time, even though there may be circular references... first
    448 // all references are dropped, and all use counts go to zero.  Then everything
    449 // is deleted for real.  Note that no operations are valid on an object that
    450 // has "dropped all references", except operator delete.
    451 //
    452 void Module::dropAllReferences() {
    453   for (Function &F : *this)
    454     F.dropAllReferences();
    455 
    456   for (GlobalVariable &GV : globals())
    457     GV.dropAllReferences();
    458 
    459   for (GlobalAlias &GA : aliases())
    460     GA.dropAllReferences();
    461 
    462   for (GlobalIFunc &GIF : ifuncs())
    463     GIF.dropAllReferences();
    464 }
    465 
    466 unsigned Module::getDwarfVersion() const {
    467   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
    468   if (!Val)
    469     return 0;
    470   return cast<ConstantInt>(Val->getValue())->getZExtValue();
    471 }
    472 
    473 unsigned Module::getCodeViewFlag() const {
    474   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
    475   if (!Val)
    476     return 0;
    477   return cast<ConstantInt>(Val->getValue())->getZExtValue();
    478 }
    479 
    480 Comdat *Module::getOrInsertComdat(StringRef Name) {
    481   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
    482   Entry.second.Name = &Entry;
    483   return &Entry.second;
    484 }
    485 
    486 PICLevel::Level Module::getPICLevel() const {
    487   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
    488 
    489   if (!Val)
    490     return PICLevel::NotPIC;
    491 
    492   return static_cast<PICLevel::Level>(
    493       cast<ConstantInt>(Val->getValue())->getZExtValue());
    494 }
    495 
    496 void Module::setPICLevel(PICLevel::Level PL) {
    497   addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
    498 }
    499 
    500 PIELevel::Level Module::getPIELevel() const {
    501   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
    502 
    503   if (!Val)
    504     return PIELevel::Default;
    505 
    506   return static_cast<PIELevel::Level>(
    507       cast<ConstantInt>(Val->getValue())->getZExtValue());
    508 }
    509 
    510 void Module::setPIELevel(PIELevel::Level PL) {
    511   addModuleFlag(ModFlagBehavior::Error, "PIE Level", PL);
    512 }
    513 
    514 void Module::setProfileSummary(Metadata *M) {
    515   addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
    516 }
    517 
    518 Metadata *Module::getProfileSummary() {
    519   return getModuleFlag("ProfileSummary");
    520 }
    521 
    522 GlobalVariable *llvm::collectUsedGlobalVariables(
    523     const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
    524   const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
    525   GlobalVariable *GV = M.getGlobalVariable(Name);
    526   if (!GV || !GV->hasInitializer())
    527     return GV;
    528 
    529   const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
    530   for (Value *Op : Init->operands()) {
    531     GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
    532     Set.insert(G);
    533   }
    534   return GV;
    535 }
    536