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(Value *V, ModFlagBehavior &MFB) { 264 if (ConstantInt *Behavior = dyn_cast<ConstantInt>(V)) { 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 Value *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 Value *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 Value *Val) { 325 Type *Int32Ty = Type::getInt32Ty(Context); 326 Value *Ops[3] = { 327 ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val 328 }; 329 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 330 } 331 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 332 uint32_t Val) { 333 Type *Int32Ty = Type::getInt32Ty(Context); 334 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 335 } 336 void Module::addModuleFlag(MDNode *Node) { 337 assert(Node->getNumOperands() == 3 && 338 "Invalid number of operands for module flag!"); 339 assert(isa<ConstantInt>(Node->getOperand(0)) && 340 isa<MDString>(Node->getOperand(1)) && 341 "Invalid operand types for module flag!"); 342 getOrInsertModuleFlagsMetadata()->addOperand(Node); 343 } 344 345 void Module::setDataLayout(StringRef Desc) { 346 DL.reset(Desc); 347 348 if (Desc.empty()) { 349 DataLayoutStr = ""; 350 } else { 351 DataLayoutStr = DL.getStringRepresentation(); 352 // DataLayoutStr is now equivalent to Desc, but since the representation 353 // is not unique, they may not be identical. 354 } 355 } 356 357 void Module::setDataLayout(const DataLayout *Other) { 358 if (!Other) { 359 DataLayoutStr = ""; 360 DL.reset(""); 361 } else { 362 DL = *Other; 363 DataLayoutStr = DL.getStringRepresentation(); 364 } 365 } 366 367 const DataLayout *Module::getDataLayout() const { 368 if (DataLayoutStr.empty()) 369 return nullptr; 370 return &DL; 371 } 372 373 // We want reproducible builds, but ModuleID may be a full path so we just use 374 // the filename to salt the RNG (although it is not guaranteed to be unique). 375 RandomNumberGenerator &Module::getRNG() const { 376 if (RNG == nullptr) { 377 StringRef Salt = sys::path::filename(ModuleID); 378 RNG = new RandomNumberGenerator(Salt); 379 } 380 return *RNG; 381 } 382 383 //===----------------------------------------------------------------------===// 384 // Methods to control the materialization of GlobalValues in the Module. 385 // 386 void Module::setMaterializer(GVMaterializer *GVM) { 387 assert(!Materializer && 388 "Module already has a GVMaterializer. Call MaterializeAllPermanently" 389 " to clear it out before setting another one."); 390 Materializer.reset(GVM); 391 } 392 393 bool Module::isDematerializable(const GlobalValue *GV) const { 394 if (Materializer) 395 return Materializer->isDematerializable(GV); 396 return false; 397 } 398 399 std::error_code Module::materialize(GlobalValue *GV) { 400 if (!Materializer) 401 return std::error_code(); 402 403 return Materializer->materialize(GV); 404 } 405 406 void Module::Dematerialize(GlobalValue *GV) { 407 if (Materializer) 408 return Materializer->Dematerialize(GV); 409 } 410 411 std::error_code Module::materializeAll() { 412 if (!Materializer) 413 return std::error_code(); 414 return Materializer->MaterializeModule(this); 415 } 416 417 std::error_code Module::materializeAllPermanently() { 418 if (std::error_code EC = materializeAll()) 419 return EC; 420 421 Materializer.reset(); 422 return std::error_code(); 423 } 424 425 //===----------------------------------------------------------------------===// 426 // Other module related stuff. 427 // 428 429 std::vector<StructType *> Module::getIdentifiedStructTypes() const { 430 // If we have a materializer, it is possible that some unread function 431 // uses a type that is currently not visible to a TypeFinder, so ask 432 // the materializer which types it created. 433 if (Materializer) 434 return Materializer->getIdentifiedStructTypes(); 435 436 std::vector<StructType *> Ret; 437 TypeFinder SrcStructTypes; 438 SrcStructTypes.run(*this, true); 439 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end()); 440 return Ret; 441 } 442 443 // dropAllReferences() - This function causes all the subelements to "let go" 444 // of all references that they are maintaining. This allows one to 'delete' a 445 // whole module at a time, even though there may be circular references... first 446 // all references are dropped, and all use counts go to zero. Then everything 447 // is deleted for real. Note that no operations are valid on an object that 448 // has "dropped all references", except operator delete. 449 // 450 void Module::dropAllReferences() { 451 for (Function &F : *this) 452 F.dropAllReferences(); 453 454 for (GlobalVariable &GV : globals()) 455 GV.dropAllReferences(); 456 457 for (GlobalAlias &GA : aliases()) 458 GA.dropAllReferences(); 459 } 460 461 unsigned Module::getDwarfVersion() const { 462 Value *Val = getModuleFlag("Dwarf Version"); 463 if (!Val) 464 return dwarf::DWARF_VERSION; 465 return cast<ConstantInt>(Val)->getZExtValue(); 466 } 467 468 Comdat *Module::getOrInsertComdat(StringRef Name) { 469 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first; 470 Entry.second.Name = &Entry; 471 return &Entry.second; 472 } 473 474 PICLevel::Level Module::getPICLevel() const { 475 Value *Val = getModuleFlag("PIC Level"); 476 477 if (Val == NULL) 478 return PICLevel::Default; 479 480 return static_cast<PICLevel::Level>(cast<ConstantInt>(Val)->getZExtValue()); 481 } 482 483 void Module::setPICLevel(PICLevel::Level PL) { 484 addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL); 485 } 486