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