LLVM API Documentation

Module.cpp
Go to the documentation of this file.
00001 //===-- Module.cpp - Implement the Module class ---------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Module class for the IR library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Module.h"
00015 #include "SymbolTableListTraitsImpl.h"
00016 #include "llvm/ADT/DenseSet.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallString.h"
00019 #include "llvm/ADT/StringExtras.h"
00020 #include "llvm/IR/Constants.h"
00021 #include "llvm/IR/DerivedTypes.h"
00022 #include "llvm/IR/GVMaterializer.h"
00023 #include "llvm/IR/InstrTypes.h"
00024 #include "llvm/IR/LLVMContext.h"
00025 #include "llvm/IR/TypeFinder.h"
00026 #include "llvm/Support/Dwarf.h"
00027 #include "llvm/Support/Path.h"
00028 #include "llvm/Support/RandomNumberGenerator.h"
00029 #include <algorithm>
00030 #include <cstdarg>
00031 #include <cstdlib>
00032 using namespace llvm;
00033 
00034 //===----------------------------------------------------------------------===//
00035 // Methods to implement the globals and functions lists.
00036 //
00037 
00038 // Explicit instantiations of SymbolTableListTraits since some of the methods
00039 // are not in the public header file.
00040 template class llvm::SymbolTableListTraits<Function, Module>;
00041 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
00042 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
00043 
00044 //===----------------------------------------------------------------------===//
00045 // Primitive Module methods.
00046 //
00047 
00048 Module::Module(StringRef MID, LLVMContext &C)
00049     : Context(C), Materializer(), ModuleID(MID), DL("") {
00050   ValSymTab = new ValueSymbolTable();
00051   NamedMDSymTab = new StringMap<NamedMDNode *>();
00052   Context.addModule(this);
00053 }
00054 
00055 Module::~Module() {
00056   Context.removeModule(this);
00057   dropAllReferences();
00058   GlobalList.clear();
00059   FunctionList.clear();
00060   AliasList.clear();
00061   NamedMDList.clear();
00062   delete ValSymTab;
00063   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
00064 }
00065 
00066 RandomNumberGenerator *Module::createRNG(const Pass* P) const {
00067   SmallString<32> Salt(P->getPassName());
00068 
00069   // This RNG is guaranteed to produce the same random stream only
00070   // when the Module ID and thus the input filename is the same. This
00071   // might be problematic if the input filename extension changes
00072   // (e.g. from .c to .bc or .ll).
00073   //
00074   // We could store this salt in NamedMetadata, but this would make
00075   // the parameter non-const. This would unfortunately make this
00076   // interface unusable by any Machine passes, since they only have a
00077   // const reference to their IR Module. Alternatively we can always
00078   // store salt metadata from the Module constructor.
00079   Salt += sys::path::filename(getModuleIdentifier());
00080 
00081   return new RandomNumberGenerator(Salt);
00082 }
00083 
00084 
00085 /// getNamedValue - Return the first global value in the module with
00086 /// the specified name, of arbitrary type.  This method returns null
00087 /// if a global with the specified name is not found.
00088 GlobalValue *Module::getNamedValue(StringRef Name) const {
00089   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
00090 }
00091 
00092 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
00093 /// This ID is uniqued across modules in the current LLVMContext.
00094 unsigned Module::getMDKindID(StringRef Name) const {
00095   return Context.getMDKindID(Name);
00096 }
00097 
00098 /// getMDKindNames - Populate client supplied SmallVector with the name for
00099 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
00100 /// so it is filled in as an empty string.
00101 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
00102   return Context.getMDKindNames(Result);
00103 }
00104 
00105 
00106 //===----------------------------------------------------------------------===//
00107 // Methods for easy access to the functions in the module.
00108 //
00109 
00110 // getOrInsertFunction - Look up the specified function in the module symbol
00111 // table.  If it does not exist, add a prototype for the function and return
00112 // it.  This is nice because it allows most passes to get away with not handling
00113 // the symbol table directly for this common task.
00114 //
00115 Constant *Module::getOrInsertFunction(StringRef Name,
00116                                       FunctionType *Ty,
00117                                       AttributeSet AttributeList) {
00118   // See if we have a definition for the specified function already.
00119   GlobalValue *F = getNamedValue(Name);
00120   if (!F) {
00121     // Nope, add it
00122     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
00123     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
00124       New->setAttributes(AttributeList);
00125     FunctionList.push_back(New);
00126     return New;                    // Return the new prototype.
00127   }
00128 
00129   // If the function exists but has the wrong type, return a bitcast to the
00130   // right type.
00131   if (F->getType() != PointerType::getUnqual(Ty))
00132     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
00133 
00134   // Otherwise, we just found the existing function or a prototype.
00135   return F;
00136 }
00137 
00138 Constant *Module::getOrInsertFunction(StringRef Name,
00139                                       FunctionType *Ty) {
00140   return getOrInsertFunction(Name, Ty, AttributeSet());
00141 }
00142 
00143 // getOrInsertFunction - Look up the specified function in the module symbol
00144 // table.  If it does not exist, add a prototype for the function and return it.
00145 // This version of the method takes a null terminated list of function
00146 // arguments, which makes it easier for clients to use.
00147 //
00148 Constant *Module::getOrInsertFunction(StringRef Name,
00149                                       AttributeSet AttributeList,
00150                                       Type *RetTy, ...) {
00151   va_list Args;
00152   va_start(Args, RetTy);
00153 
00154   // Build the list of argument types...
00155   std::vector<Type*> ArgTys;
00156   while (Type *ArgTy = va_arg(Args, Type*))
00157     ArgTys.push_back(ArgTy);
00158 
00159   va_end(Args);
00160 
00161   // Build the function type and chain to the other getOrInsertFunction...
00162   return getOrInsertFunction(Name,
00163                              FunctionType::get(RetTy, ArgTys, false),
00164                              AttributeList);
00165 }
00166 
00167 Constant *Module::getOrInsertFunction(StringRef Name,
00168                                       Type *RetTy, ...) {
00169   va_list Args;
00170   va_start(Args, RetTy);
00171 
00172   // Build the list of argument types...
00173   std::vector<Type*> ArgTys;
00174   while (Type *ArgTy = va_arg(Args, Type*))
00175     ArgTys.push_back(ArgTy);
00176 
00177   va_end(Args);
00178 
00179   // Build the function type and chain to the other getOrInsertFunction...
00180   return getOrInsertFunction(Name,
00181                              FunctionType::get(RetTy, ArgTys, false),
00182                              AttributeSet());
00183 }
00184 
00185 // getFunction - Look up the specified function in the module symbol table.
00186 // If it does not exist, return null.
00187 //
00188 Function *Module::getFunction(StringRef Name) const {
00189   return dyn_cast_or_null<Function>(getNamedValue(Name));
00190 }
00191 
00192 //===----------------------------------------------------------------------===//
00193 // Methods for easy access to the global variables in the module.
00194 //
00195 
00196 /// getGlobalVariable - Look up the specified global variable in the module
00197 /// symbol table.  If it does not exist, return null.  The type argument
00198 /// should be the underlying type of the global, i.e., it should not have
00199 /// the top-level PointerType, which represents the address of the global.
00200 /// If AllowLocal is set to true, this function will return types that
00201 /// have an local. By default, these types are not returned.
00202 ///
00203 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
00204   if (GlobalVariable *Result =
00205       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
00206     if (AllowLocal || !Result->hasLocalLinkage())
00207       return Result;
00208   return nullptr;
00209 }
00210 
00211 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
00212 ///   1. If it does not exist, add a declaration of the global and return it.
00213 ///   2. Else, the global exists but has the wrong type: return the function
00214 ///      with a constantexpr cast to the right type.
00215 ///   3. Finally, if the existing global is the correct declaration, return the
00216 ///      existing global.
00217 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
00218   // See if we have a definition for the specified global already.
00219   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
00220   if (!GV) {
00221     // Nope, add it
00222     GlobalVariable *New =
00223       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
00224                          nullptr, Name);
00225      return New;                    // Return the new declaration.
00226   }
00227 
00228   // If the variable exists but has the wrong type, return a bitcast to the
00229   // right type.
00230   Type *GVTy = GV->getType();
00231   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
00232   if (GVTy != PTy)
00233     return ConstantExpr::getBitCast(GV, PTy);
00234 
00235   // Otherwise, we just found the existing function or a prototype.
00236   return GV;
00237 }
00238 
00239 //===----------------------------------------------------------------------===//
00240 // Methods for easy access to the global variables in the module.
00241 //
00242 
00243 // getNamedAlias - Look up the specified global in the module symbol table.
00244 // If it does not exist, return null.
00245 //
00246 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
00247   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
00248 }
00249 
00250 /// getNamedMetadata - Return the first NamedMDNode in the module with the
00251 /// specified name. This method returns null if a NamedMDNode with the
00252 /// specified name is not found.
00253 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
00254   SmallString<256> NameData;
00255   StringRef NameRef = Name.toStringRef(NameData);
00256   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
00257 }
00258 
00259 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
00260 /// with the specified name. This method returns a new NamedMDNode if a
00261 /// NamedMDNode with the specified name is not found.
00262 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
00263   NamedMDNode *&NMD =
00264     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
00265   if (!NMD) {
00266     NMD = new NamedMDNode(Name);
00267     NMD->setParent(this);
00268     NamedMDList.push_back(NMD);
00269   }
00270   return NMD;
00271 }
00272 
00273 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
00274 /// delete it.
00275 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
00276   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
00277   NamedMDList.erase(NMD);
00278 }
00279 
00280 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
00281   if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
00282     uint64_t Val = Behavior->getLimitedValue();
00283     if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
00284       MFB = static_cast<ModFlagBehavior>(Val);
00285       return true;
00286     }
00287   }
00288   return false;
00289 }
00290 
00291 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
00292 void Module::
00293 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
00294   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
00295   if (!ModFlags) return;
00296 
00297   for (const MDNode *Flag : ModFlags->operands()) {
00298     ModFlagBehavior MFB;
00299     if (Flag->getNumOperands() >= 3 &&
00300         isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
00301         dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
00302       // Check the operands of the MDNode before accessing the operands.
00303       // The verifier will actually catch these failures.
00304       MDString *Key = cast<MDString>(Flag->getOperand(1));
00305       Metadata *Val = Flag->getOperand(2);
00306       Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
00307     }
00308   }
00309 }
00310 
00311 /// Return the corresponding value if Key appears in module flags, otherwise
00312 /// return null.
00313 Metadata *Module::getModuleFlag(StringRef Key) const {
00314   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
00315   getModuleFlagsMetadata(ModuleFlags);
00316   for (const ModuleFlagEntry &MFE : ModuleFlags) {
00317     if (Key == MFE.Key->getString())
00318       return MFE.Val;
00319   }
00320   return nullptr;
00321 }
00322 
00323 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
00324 /// represents module-level flags. This method returns null if there are no
00325 /// module-level flags.
00326 NamedMDNode *Module::getModuleFlagsMetadata() const {
00327   return getNamedMetadata("llvm.module.flags");
00328 }
00329 
00330 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
00331 /// represents module-level flags. If module-level flags aren't found, it
00332 /// creates the named metadata that contains them.
00333 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
00334   return getOrInsertNamedMetadata("llvm.module.flags");
00335 }
00336 
00337 /// addModuleFlag - Add a module-level flag to the module-level flags
00338 /// metadata. It will create the module-level flags named metadata if it doesn't
00339 /// already exist.
00340 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
00341                            Metadata *Val) {
00342   Type *Int32Ty = Type::getInt32Ty(Context);
00343   Metadata *Ops[3] = {
00344       ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
00345       MDString::get(Context, Key), Val};
00346   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
00347 }
00348 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
00349                            Constant *Val) {
00350   addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
00351 }
00352 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
00353                            uint32_t Val) {
00354   Type *Int32Ty = Type::getInt32Ty(Context);
00355   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
00356 }
00357 void Module::addModuleFlag(MDNode *Node) {
00358   assert(Node->getNumOperands() == 3 &&
00359          "Invalid number of operands for module flag!");
00360   assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
00361          isa<MDString>(Node->getOperand(1)) &&
00362          "Invalid operand types for module flag!");
00363   getOrInsertModuleFlagsMetadata()->addOperand(Node);
00364 }
00365 
00366 void Module::setDataLayout(StringRef Desc) {
00367   DL.reset(Desc);
00368 
00369   if (Desc.empty()) {
00370     DataLayoutStr = "";
00371   } else {
00372     DataLayoutStr = DL.getStringRepresentation();
00373     // DataLayoutStr is now equivalent to Desc, but since the representation
00374     // is not unique, they may not be identical.
00375   }
00376 }
00377 
00378 void Module::setDataLayout(const DataLayout *Other) {
00379   if (!Other) {
00380     DataLayoutStr = "";
00381     DL.reset("");
00382   } else {
00383     DL = *Other;
00384     DataLayoutStr = DL.getStringRepresentation();
00385   }
00386 }
00387 
00388 const DataLayout *Module::getDataLayout() const {
00389   if (DataLayoutStr.empty())
00390     return nullptr;
00391   return &DL;
00392 }
00393 
00394 //===----------------------------------------------------------------------===//
00395 // Methods to control the materialization of GlobalValues in the Module.
00396 //
00397 void Module::setMaterializer(GVMaterializer *GVM) {
00398   assert(!Materializer &&
00399          "Module already has a GVMaterializer.  Call MaterializeAllPermanently"
00400          " to clear it out before setting another one.");
00401   Materializer.reset(GVM);
00402 }
00403 
00404 bool Module::isDematerializable(const GlobalValue *GV) const {
00405   if (Materializer)
00406     return Materializer->isDematerializable(GV);
00407   return false;
00408 }
00409 
00410 std::error_code Module::materialize(GlobalValue *GV) {
00411   if (!Materializer)
00412     return std::error_code();
00413 
00414   return Materializer->materialize(GV);
00415 }
00416 
00417 void Module::Dematerialize(GlobalValue *GV) {
00418   if (Materializer)
00419     return Materializer->Dematerialize(GV);
00420 }
00421 
00422 std::error_code Module::materializeAll() {
00423   if (!Materializer)
00424     return std::error_code();
00425   return Materializer->MaterializeModule(this);
00426 }
00427 
00428 std::error_code Module::materializeAllPermanently() {
00429   if (std::error_code EC = materializeAll())
00430     return EC;
00431 
00432   Materializer.reset();
00433   return std::error_code();
00434 }
00435 
00436 //===----------------------------------------------------------------------===//
00437 // Other module related stuff.
00438 //
00439 
00440 std::vector<StructType *> Module::getIdentifiedStructTypes() const {
00441   // If we have a materializer, it is possible that some unread function
00442   // uses a type that is currently not visible to a TypeFinder, so ask
00443   // the materializer which types it created.
00444   if (Materializer)
00445     return Materializer->getIdentifiedStructTypes();
00446 
00447   std::vector<StructType *> Ret;
00448   TypeFinder SrcStructTypes;
00449   SrcStructTypes.run(*this, true);
00450   Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
00451   return Ret;
00452 }
00453 
00454 // dropAllReferences() - This function causes all the subelements to "let go"
00455 // of all references that they are maintaining.  This allows one to 'delete' a
00456 // whole module at a time, even though there may be circular references... first
00457 // all references are dropped, and all use counts go to zero.  Then everything
00458 // is deleted for real.  Note that no operations are valid on an object that
00459 // has "dropped all references", except operator delete.
00460 //
00461 void Module::dropAllReferences() {
00462   for (Function &F : *this)
00463     F.dropAllReferences();
00464 
00465   for (GlobalVariable &GV : globals())
00466     GV.dropAllReferences();
00467 
00468   for (GlobalAlias &GA : aliases())
00469     GA.dropAllReferences();
00470 }
00471 
00472 unsigned Module::getDwarfVersion() const {
00473   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
00474   if (!Val)
00475     return dwarf::DWARF_VERSION;
00476   return cast<ConstantInt>(Val->getValue())->getZExtValue();
00477 }
00478 
00479 Comdat *Module::getOrInsertComdat(StringRef Name) {
00480   auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
00481   Entry.second.Name = &Entry;
00482   return &Entry.second;
00483 }
00484 
00485 PICLevel::Level Module::getPICLevel() const {
00486   auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
00487 
00488   if (Val == NULL)
00489     return PICLevel::Default;
00490 
00491   return static_cast<PICLevel::Level>(
00492       cast<ConstantInt>(Val->getValue())->getZExtValue());
00493 }
00494 
00495 void Module::setPICLevel(PICLevel::Level PL) {
00496   addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
00497 }