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/LeakDetector.h"
00026 #include <algorithm>
00027 #include <cstdarg>
00028 #include <cstdlib>
00029 using namespace llvm;
00030 
00031 //===----------------------------------------------------------------------===//
00032 // Methods to implement the globals and functions lists.
00033 //
00034 
00035 // Explicit instantiations of SymbolTableListTraits since some of the methods
00036 // are not in the public header file.
00037 template class llvm::SymbolTableListTraits<Function, Module>;
00038 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
00039 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
00040 
00041 //===----------------------------------------------------------------------===//
00042 // Primitive Module methods.
00043 //
00044 
00045 Module::Module(StringRef MID, LLVMContext &C)
00046     : Context(C), Materializer(), ModuleID(MID), DL("") {
00047   ValSymTab = new ValueSymbolTable();
00048   NamedMDSymTab = new StringMap<NamedMDNode *>();
00049   Context.addModule(this);
00050 }
00051 
00052 Module::~Module() {
00053   Context.removeModule(this);
00054   dropAllReferences();
00055   GlobalList.clear();
00056   FunctionList.clear();
00057   AliasList.clear();
00058   NamedMDList.clear();
00059   delete ValSymTab;
00060   delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
00061 }
00062 
00063 /// getNamedValue - Return the first global value in the module with
00064 /// the specified name, of arbitrary type.  This method returns null
00065 /// if a global with the specified name is not found.
00066 GlobalValue *Module::getNamedValue(StringRef Name) const {
00067   return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
00068 }
00069 
00070 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
00071 /// This ID is uniqued across modules in the current LLVMContext.
00072 unsigned Module::getMDKindID(StringRef Name) const {
00073   return Context.getMDKindID(Name);
00074 }
00075 
00076 /// getMDKindNames - Populate client supplied SmallVector with the name for
00077 /// custom metadata IDs registered in this LLVMContext.   ID #0 is not used,
00078 /// so it is filled in as an empty string.
00079 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
00080   return Context.getMDKindNames(Result);
00081 }
00082 
00083 
00084 //===----------------------------------------------------------------------===//
00085 // Methods for easy access to the functions in the module.
00086 //
00087 
00088 // getOrInsertFunction - Look up the specified function in the module symbol
00089 // table.  If it does not exist, add a prototype for the function and return
00090 // it.  This is nice because it allows most passes to get away with not handling
00091 // the symbol table directly for this common task.
00092 //
00093 Constant *Module::getOrInsertFunction(StringRef Name,
00094                                       FunctionType *Ty,
00095                                       AttributeSet AttributeList) {
00096   // See if we have a definition for the specified function already.
00097   GlobalValue *F = getNamedValue(Name);
00098   if (!F) {
00099     // Nope, add it
00100     Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
00101     if (!New->isIntrinsic())       // Intrinsics get attrs set on construction
00102       New->setAttributes(AttributeList);
00103     FunctionList.push_back(New);
00104     return New;                    // Return the new prototype.
00105   }
00106 
00107   // If the function exists but has the wrong type, return a bitcast to the
00108   // right type.
00109   if (F->getType() != PointerType::getUnqual(Ty))
00110     return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
00111 
00112   // Otherwise, we just found the existing function or a prototype.
00113   return F;
00114 }
00115 
00116 Constant *Module::getOrInsertFunction(StringRef Name,
00117                                       FunctionType *Ty) {
00118   return getOrInsertFunction(Name, Ty, AttributeSet());
00119 }
00120 
00121 // getOrInsertFunction - Look up the specified function in the module symbol
00122 // table.  If it does not exist, add a prototype for the function and return it.
00123 // This version of the method takes a null terminated list of function
00124 // arguments, which makes it easier for clients to use.
00125 //
00126 Constant *Module::getOrInsertFunction(StringRef Name,
00127                                       AttributeSet AttributeList,
00128                                       Type *RetTy, ...) {
00129   va_list Args;
00130   va_start(Args, RetTy);
00131 
00132   // Build the list of argument types...
00133   std::vector<Type*> ArgTys;
00134   while (Type *ArgTy = va_arg(Args, Type*))
00135     ArgTys.push_back(ArgTy);
00136 
00137   va_end(Args);
00138 
00139   // Build the function type and chain to the other getOrInsertFunction...
00140   return getOrInsertFunction(Name,
00141                              FunctionType::get(RetTy, ArgTys, false),
00142                              AttributeList);
00143 }
00144 
00145 Constant *Module::getOrInsertFunction(StringRef Name,
00146                                       Type *RetTy, ...) {
00147   va_list Args;
00148   va_start(Args, RetTy);
00149 
00150   // Build the list of argument types...
00151   std::vector<Type*> ArgTys;
00152   while (Type *ArgTy = va_arg(Args, Type*))
00153     ArgTys.push_back(ArgTy);
00154 
00155   va_end(Args);
00156 
00157   // Build the function type and chain to the other getOrInsertFunction...
00158   return getOrInsertFunction(Name,
00159                              FunctionType::get(RetTy, ArgTys, false),
00160                              AttributeSet());
00161 }
00162 
00163 // getFunction - Look up the specified function in the module symbol table.
00164 // If it does not exist, return null.
00165 //
00166 Function *Module::getFunction(StringRef Name) const {
00167   return dyn_cast_or_null<Function>(getNamedValue(Name));
00168 }
00169 
00170 //===----------------------------------------------------------------------===//
00171 // Methods for easy access to the global variables in the module.
00172 //
00173 
00174 /// getGlobalVariable - Look up the specified global variable in the module
00175 /// symbol table.  If it does not exist, return null.  The type argument
00176 /// should be the underlying type of the global, i.e., it should not have
00177 /// the top-level PointerType, which represents the address of the global.
00178 /// If AllowLocal is set to true, this function will return types that
00179 /// have an local. By default, these types are not returned.
00180 ///
00181 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
00182   if (GlobalVariable *Result =
00183       dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
00184     if (AllowLocal || !Result->hasLocalLinkage())
00185       return Result;
00186   return nullptr;
00187 }
00188 
00189 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
00190 ///   1. If it does not exist, add a declaration of the global and return it.
00191 ///   2. Else, the global exists but has the wrong type: return the function
00192 ///      with a constantexpr cast to the right type.
00193 ///   3. Finally, if the existing global is the correct declaration, return the
00194 ///      existing global.
00195 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
00196   // See if we have a definition for the specified global already.
00197   GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
00198   if (!GV) {
00199     // Nope, add it
00200     GlobalVariable *New =
00201       new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
00202                          nullptr, Name);
00203      return New;                    // Return the new declaration.
00204   }
00205 
00206   // If the variable exists but has the wrong type, return a bitcast to the
00207   // right type.
00208   Type *GVTy = GV->getType();
00209   PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
00210   if (GVTy != PTy)
00211     return ConstantExpr::getBitCast(GV, PTy);
00212 
00213   // Otherwise, we just found the existing function or a prototype.
00214   return GV;
00215 }
00216 
00217 //===----------------------------------------------------------------------===//
00218 // Methods for easy access to the global variables in the module.
00219 //
00220 
00221 // getNamedAlias - Look up the specified global in the module symbol table.
00222 // If it does not exist, return null.
00223 //
00224 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
00225   return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
00226 }
00227 
00228 /// getNamedMetadata - Return the first NamedMDNode in the module with the
00229 /// specified name. This method returns null if a NamedMDNode with the
00230 /// specified name is not found.
00231 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
00232   SmallString<256> NameData;
00233   StringRef NameRef = Name.toStringRef(NameData);
00234   return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
00235 }
00236 
00237 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
00238 /// with the specified name. This method returns a new NamedMDNode if a
00239 /// NamedMDNode with the specified name is not found.
00240 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
00241   NamedMDNode *&NMD =
00242     (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
00243   if (!NMD) {
00244     NMD = new NamedMDNode(Name);
00245     NMD->setParent(this);
00246     NamedMDList.push_back(NMD);
00247   }
00248   return NMD;
00249 }
00250 
00251 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
00252 /// delete it.
00253 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
00254   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
00255   NamedMDList.erase(NMD);
00256 }
00257 
00258 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
00259 void Module::
00260 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
00261   const NamedMDNode *ModFlags = getModuleFlagsMetadata();
00262   if (!ModFlags) return;
00263 
00264   for (const MDNode *Flag : ModFlags->operands()) {
00265     if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) &&
00266         isa<MDString>(Flag->getOperand(1))) {
00267       // Check the operands of the MDNode before accessing the operands.
00268       // The verifier will actually catch these failures.
00269       ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
00270       MDString *Key = cast<MDString>(Flag->getOperand(1));
00271       Value *Val = Flag->getOperand(2);
00272       Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
00273                                       Key, Val));
00274     }
00275   }
00276 }
00277 
00278 /// Return the corresponding value if Key appears in module flags, otherwise
00279 /// return null.
00280 Value *Module::getModuleFlag(StringRef Key) const {
00281   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
00282   getModuleFlagsMetadata(ModuleFlags);
00283   for (const ModuleFlagEntry &MFE : ModuleFlags) {
00284     if (Key == MFE.Key->getString())
00285       return MFE.Val;
00286   }
00287   return nullptr;
00288 }
00289 
00290 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
00291 /// represents module-level flags. This method returns null if there are no
00292 /// module-level flags.
00293 NamedMDNode *Module::getModuleFlagsMetadata() const {
00294   return getNamedMetadata("llvm.module.flags");
00295 }
00296 
00297 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
00298 /// represents module-level flags. If module-level flags aren't found, it
00299 /// creates the named metadata that contains them.
00300 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
00301   return getOrInsertNamedMetadata("llvm.module.flags");
00302 }
00303 
00304 /// addModuleFlag - Add a module-level flag to the module-level flags
00305 /// metadata. It will create the module-level flags named metadata if it doesn't
00306 /// already exist.
00307 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
00308                            Value *Val) {
00309   Type *Int32Ty = Type::getInt32Ty(Context);
00310   Value *Ops[3] = {
00311     ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
00312   };
00313   getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
00314 }
00315 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
00316                            uint32_t Val) {
00317   Type *Int32Ty = Type::getInt32Ty(Context);
00318   addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
00319 }
00320 void Module::addModuleFlag(MDNode *Node) {
00321   assert(Node->getNumOperands() == 3 &&
00322          "Invalid number of operands for module flag!");
00323   assert(isa<ConstantInt>(Node->getOperand(0)) &&
00324          isa<MDString>(Node->getOperand(1)) &&
00325          "Invalid operand types for module flag!");
00326   getOrInsertModuleFlagsMetadata()->addOperand(Node);
00327 }
00328 
00329 void Module::setDataLayout(StringRef Desc) {
00330   DL.reset(Desc);
00331 
00332   if (Desc.empty()) {
00333     DataLayoutStr = "";
00334   } else {
00335     DataLayoutStr = DL.getStringRepresentation();
00336     // DataLayoutStr is now equivalent to Desc, but since the representation
00337     // is not unique, they may not be identical.
00338   }
00339 }
00340 
00341 void Module::setDataLayout(const DataLayout *Other) {
00342   if (!Other) {
00343     DataLayoutStr = "";
00344     DL.reset("");
00345   } else {
00346     DL = *Other;
00347     DataLayoutStr = DL.getStringRepresentation();
00348   }
00349 }
00350 
00351 const DataLayout *Module::getDataLayout() const {
00352   if (DataLayoutStr.empty())
00353     return nullptr;
00354   return &DL;
00355 }
00356 
00357 //===----------------------------------------------------------------------===//
00358 // Methods to control the materialization of GlobalValues in the Module.
00359 //
00360 void Module::setMaterializer(GVMaterializer *GVM) {
00361   assert(!Materializer &&
00362          "Module already has a GVMaterializer.  Call MaterializeAllPermanently"
00363          " to clear it out before setting another one.");
00364   Materializer.reset(GVM);
00365 }
00366 
00367 bool Module::isMaterializable(const GlobalValue *GV) const {
00368   if (Materializer)
00369     return Materializer->isMaterializable(GV);
00370   return false;
00371 }
00372 
00373 bool Module::isDematerializable(const GlobalValue *GV) const {
00374   if (Materializer)
00375     return Materializer->isDematerializable(GV);
00376   return false;
00377 }
00378 
00379 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
00380   if (!Materializer)
00381     return false;
00382 
00383   error_code EC = Materializer->Materialize(GV);
00384   if (!EC)
00385     return false;
00386   if (ErrInfo)
00387     *ErrInfo = EC.message();
00388   return true;
00389 }
00390 
00391 void Module::Dematerialize(GlobalValue *GV) {
00392   if (Materializer)
00393     return Materializer->Dematerialize(GV);
00394 }
00395 
00396 error_code Module::materializeAll() {
00397   if (!Materializer)
00398     return error_code::success();
00399   return Materializer->MaterializeModule(this);
00400 }
00401 
00402 error_code Module::materializeAllPermanently() {
00403   if (error_code EC = materializeAll())
00404     return EC;
00405 
00406   Materializer.reset();
00407   return error_code::success();
00408 }
00409 
00410 //===----------------------------------------------------------------------===//
00411 // Other module related stuff.
00412 //
00413 
00414 
00415 // dropAllReferences() - This function causes all the subelements to "let go"
00416 // of all references that they are maintaining.  This allows one to 'delete' a
00417 // whole module at a time, even though there may be circular references... first
00418 // all references are dropped, and all use counts go to zero.  Then everything
00419 // is deleted for real.  Note that no operations are valid on an object that
00420 // has "dropped all references", except operator delete.
00421 //
00422 void Module::dropAllReferences() {
00423   for(Module::iterator I = begin(), E = end(); I != E; ++I)
00424     I->dropAllReferences();
00425 
00426   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
00427     I->dropAllReferences();
00428 
00429   for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
00430     I->dropAllReferences();
00431 }