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/DenseSet.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/GVMaterializer.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DerivedTypes.h" 23 #include "llvm/IR/InstrTypes.h" 24 #include "llvm/IR/LLVMContext.h" 25 #include "llvm/Support/LeakDetector.h" 26 #include <algorithm> 27 #include <cstdarg> 28 #include <cstdlib> 29 using namespace llvm; 30 31 //===----------------------------------------------------------------------===// 32 // Methods to implement the globals and functions lists. 33 // 34 35 // Explicit instantiations of SymbolTableListTraits since some of the methods 36 // are not in the public header file. 37 template class llvm::SymbolTableListTraits<Function, Module>; 38 template class llvm::SymbolTableListTraits<GlobalVariable, Module>; 39 template class llvm::SymbolTableListTraits<GlobalAlias, Module>; 40 41 //===----------------------------------------------------------------------===// 42 // Primitive Module methods. 43 // 44 45 Module::Module(StringRef MID, LLVMContext& C) 46 : Context(C), Materializer(NULL), ModuleID(MID) { 47 ValSymTab = new ValueSymbolTable(); 48 NamedMDSymTab = new StringMap<NamedMDNode *>(); 49 Context.addModule(this); 50 } 51 52 Module::~Module() { 53 Context.removeModule(this); 54 dropAllReferences(); 55 GlobalList.clear(); 56 FunctionList.clear(); 57 AliasList.clear(); 58 NamedMDList.clear(); 59 delete ValSymTab; 60 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab); 61 } 62 63 /// getNamedValue - Return the first global value in the module with 64 /// the specified name, of arbitrary type. This method returns null 65 /// if a global with the specified name is not found. 66 GlobalValue *Module::getNamedValue(StringRef Name) const { 67 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name)); 68 } 69 70 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 71 /// This ID is uniqued across modules in the current LLVMContext. 72 unsigned Module::getMDKindID(StringRef Name) const { 73 return Context.getMDKindID(Name); 74 } 75 76 /// getMDKindNames - Populate client supplied SmallVector with the name for 77 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 78 /// so it is filled in as an empty string. 79 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 80 return Context.getMDKindNames(Result); 81 } 82 83 84 //===----------------------------------------------------------------------===// 85 // Methods for easy access to the functions in the module. 86 // 87 88 // getOrInsertFunction - Look up the specified function in the module symbol 89 // table. If it does not exist, add a prototype for the function and return 90 // it. This is nice because it allows most passes to get away with not handling 91 // the symbol table directly for this common task. 92 // 93 Constant *Module::getOrInsertFunction(StringRef Name, 94 FunctionType *Ty, 95 AttributeSet AttributeList) { 96 // See if we have a definition for the specified function already. 97 GlobalValue *F = getNamedValue(Name); 98 if (F == 0) { 99 // Nope, add it 100 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name); 101 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 102 New->setAttributes(AttributeList); 103 FunctionList.push_back(New); 104 return New; // Return the new prototype. 105 } 106 107 // Okay, the function exists. Does it have externally visible linkage? 108 if (F->hasLocalLinkage()) { 109 // Clear the function's name. 110 F->setName(""); 111 // Retry, now there won't be a conflict. 112 Constant *NewF = getOrInsertFunction(Name, Ty); 113 F->setName(Name); 114 return NewF; 115 } 116 117 // If the function exists but has the wrong type, return a bitcast to the 118 // right type. 119 if (F->getType() != PointerType::getUnqual(Ty)) 120 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty)); 121 122 // Otherwise, we just found the existing function or a prototype. 123 return F; 124 } 125 126 Constant *Module::getOrInsertFunction(StringRef Name, 127 FunctionType *Ty) { 128 return getOrInsertFunction(Name, Ty, AttributeSet()); 129 } 130 131 // getOrInsertFunction - Look up the specified function in the module symbol 132 // table. If it does not exist, add a prototype for the function and return it. 133 // This version of the method takes a null terminated list of function 134 // arguments, which makes it easier for clients to use. 135 // 136 Constant *Module::getOrInsertFunction(StringRef Name, 137 AttributeSet AttributeList, 138 Type *RetTy, ...) { 139 va_list Args; 140 va_start(Args, RetTy); 141 142 // Build the list of argument types... 143 std::vector<Type*> ArgTys; 144 while (Type *ArgTy = va_arg(Args, Type*)) 145 ArgTys.push_back(ArgTy); 146 147 va_end(Args); 148 149 // Build the function type and chain to the other getOrInsertFunction... 150 return getOrInsertFunction(Name, 151 FunctionType::get(RetTy, ArgTys, false), 152 AttributeList); 153 } 154 155 Constant *Module::getOrInsertFunction(StringRef Name, 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 AttributeSet()); 171 } 172 173 // getFunction - Look up the specified function in the module symbol table. 174 // If it does not exist, return null. 175 // 176 Function *Module::getFunction(StringRef Name) const { 177 return dyn_cast_or_null<Function>(getNamedValue(Name)); 178 } 179 180 //===----------------------------------------------------------------------===// 181 // Methods for easy access to the global variables in the module. 182 // 183 184 /// getGlobalVariable - Look up the specified global variable in the module 185 /// symbol table. If it does not exist, return null. The type argument 186 /// should be the underlying type of the global, i.e., it should not have 187 /// the top-level PointerType, which represents the address of the global. 188 /// If AllowLocal is set to true, this function will return types that 189 /// have an local. By default, these types are not returned. 190 /// 191 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) { 192 if (GlobalVariable *Result = 193 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 194 if (AllowLocal || !Result->hasLocalLinkage()) 195 return Result; 196 return 0; 197 } 198 199 /// getOrInsertGlobal - Look up the specified global in the module symbol table. 200 /// 1. If it does not exist, add a declaration of the global and return it. 201 /// 2. Else, the global exists but has the wrong type: return the function 202 /// with a constantexpr cast to the right type. 203 /// 3. Finally, if the existing global is the correct declaration, return the 204 /// existing global. 205 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 206 // See if we have a definition for the specified global already. 207 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)); 208 if (GV == 0) { 209 // Nope, add it 210 GlobalVariable *New = 211 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 212 0, Name); 213 return New; // Return the new declaration. 214 } 215 216 // If the variable exists but has the wrong type, return a bitcast to the 217 // right type. 218 Type *GVTy = GV->getType(); 219 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace()); 220 if (GVTy != PTy) 221 return ConstantExpr::getBitCast(GV, PTy); 222 223 // Otherwise, we just found the existing function or a prototype. 224 return GV; 225 } 226 227 //===----------------------------------------------------------------------===// 228 // Methods for easy access to the global variables in the module. 229 // 230 231 // getNamedAlias - Look up the specified global in the module symbol table. 232 // If it does not exist, return null. 233 // 234 GlobalAlias *Module::getNamedAlias(StringRef Name) const { 235 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 236 } 237 238 /// getNamedMetadata - Return the first NamedMDNode in the module with the 239 /// specified name. This method returns null if a NamedMDNode with the 240 /// specified name is not found. 241 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const { 242 SmallString<256> NameData; 243 StringRef NameRef = Name.toStringRef(NameData); 244 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef); 245 } 246 247 /// getOrInsertNamedMetadata - Return the first named MDNode in the module 248 /// with the specified name. This method returns a new NamedMDNode if a 249 /// NamedMDNode with the specified name is not found. 250 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 251 NamedMDNode *&NMD = 252 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name]; 253 if (!NMD) { 254 NMD = new NamedMDNode(Name); 255 NMD->setParent(this); 256 NamedMDList.push_back(NMD); 257 } 258 return NMD; 259 } 260 261 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and 262 /// delete it. 263 void Module::eraseNamedMetadata(NamedMDNode *NMD) { 264 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName()); 265 NamedMDList.erase(NMD); 266 } 267 268 /// getModuleFlagsMetadata - Returns the module flags in the provided vector. 269 void Module:: 270 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 271 const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 272 if (!ModFlags) return; 273 274 for (unsigned i = 0, e = ModFlags->getNumOperands(); i != e; ++i) { 275 MDNode *Flag = ModFlags->getOperand(i); 276 if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) && 277 isa<MDString>(Flag->getOperand(1))) { 278 // Check the operands of the MDNode before accessing the operands. 279 // The verifier will actually catch these failures. 280 ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0)); 281 MDString *Key = cast<MDString>(Flag->getOperand(1)); 282 Value *Val = Flag->getOperand(2); 283 Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()), 284 Key, Val)); 285 } 286 } 287 } 288 289 /// Return the corresponding value if Key appears in module flags, otherwise 290 /// return null. 291 Value *Module::getModuleFlag(StringRef Key) const { 292 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 293 getModuleFlagsMetadata(ModuleFlags); 294 for (unsigned I = 0, E = ModuleFlags.size(); I < E; ++I) { 295 const ModuleFlagEntry &MFE = ModuleFlags[I]; 296 if (Key == MFE.Key->getString()) 297 return MFE.Val; 298 } 299 return 0; 300 } 301 302 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that 303 /// represents module-level flags. This method returns null if there are no 304 /// module-level flags. 305 NamedMDNode *Module::getModuleFlagsMetadata() const { 306 return getNamedMetadata("llvm.module.flags"); 307 } 308 309 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 310 /// represents module-level flags. If module-level flags aren't found, it 311 /// creates the named metadata that contains them. 312 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 313 return getOrInsertNamedMetadata("llvm.module.flags"); 314 } 315 316 /// addModuleFlag - Add a module-level flag to the module-level flags 317 /// metadata. It will create the module-level flags named metadata if it doesn't 318 /// already exist. 319 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 320 Value *Val) { 321 Type *Int32Ty = Type::getInt32Ty(Context); 322 Value *Ops[3] = { 323 ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val 324 }; 325 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 326 } 327 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 328 uint32_t Val) { 329 Type *Int32Ty = Type::getInt32Ty(Context); 330 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 331 } 332 void Module::addModuleFlag(MDNode *Node) { 333 assert(Node->getNumOperands() == 3 && 334 "Invalid number of operands for module flag!"); 335 assert(isa<ConstantInt>(Node->getOperand(0)) && 336 isa<MDString>(Node->getOperand(1)) && 337 "Invalid operand types for module flag!"); 338 getOrInsertModuleFlagsMetadata()->addOperand(Node); 339 } 340 341 //===----------------------------------------------------------------------===// 342 // Methods to control the materialization of GlobalValues in the Module. 343 // 344 void Module::setMaterializer(GVMaterializer *GVM) { 345 assert(!Materializer && 346 "Module already has a GVMaterializer. Call MaterializeAllPermanently" 347 " to clear it out before setting another one."); 348 Materializer.reset(GVM); 349 } 350 351 bool Module::isMaterializable(const GlobalValue *GV) const { 352 if (Materializer) 353 return Materializer->isMaterializable(GV); 354 return false; 355 } 356 357 bool Module::isDematerializable(const GlobalValue *GV) const { 358 if (Materializer) 359 return Materializer->isDematerializable(GV); 360 return false; 361 } 362 363 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) { 364 if (!Materializer) 365 return false; 366 367 error_code EC = Materializer->Materialize(GV); 368 if (!EC) 369 return false; 370 if (ErrInfo) 371 *ErrInfo = EC.message(); 372 return true; 373 } 374 375 void Module::Dematerialize(GlobalValue *GV) { 376 if (Materializer) 377 return Materializer->Dematerialize(GV); 378 } 379 380 error_code Module::materializeAll() { 381 if (!Materializer) 382 return error_code::success(); 383 return Materializer->MaterializeModule(this); 384 } 385 386 error_code Module::materializeAllPermanently() { 387 if (error_code EC = materializeAll()) 388 return EC; 389 390 Materializer.reset(); 391 return error_code::success(); 392 } 393 394 //===----------------------------------------------------------------------===// 395 // Other module related stuff. 396 // 397 398 399 // dropAllReferences() - This function causes all the subelements to "let go" 400 // of all references that they are maintaining. This allows one to 'delete' a 401 // whole module at a time, even though there may be circular references... first 402 // all references are dropped, and all use counts go to zero. Then everything 403 // is deleted for real. Note that no operations are valid on an object that 404 // has "dropped all references", except operator delete. 405 // 406 void Module::dropAllReferences() { 407 for(Module::iterator I = begin(), E = end(); I != E; ++I) 408 I->dropAllReferences(); 409 410 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I) 411 I->dropAllReferences(); 412 413 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I) 414 I->dropAllReferences(); 415 } 416