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