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