1 //===- Module.cpp - Implement the Module class ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Module class for the IR library. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/Module.h" 14 #include "SymbolTableListTraitsImpl.h" 15 #include "llvm/ADT/Optional.h" 16 #include "llvm/ADT/SmallPtrSet.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/StringMap.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/ADT/Twine.h" 22 #include "llvm/IR/Attributes.h" 23 #include "llvm/IR/Comdat.h" 24 #include "llvm/IR/Constants.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/DebugInfoMetadata.h" 27 #include "llvm/IR/DerivedTypes.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/GVMaterializer.h" 30 #include "llvm/IR/GlobalAlias.h" 31 #include "llvm/IR/GlobalIFunc.h" 32 #include "llvm/IR/GlobalValue.h" 33 #include "llvm/IR/GlobalVariable.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/Metadata.h" 36 #include "llvm/IR/SymbolTableListTraits.h" 37 #include "llvm/IR/Type.h" 38 #include "llvm/IR/TypeFinder.h" 39 #include "llvm/IR/Value.h" 40 #include "llvm/IR/ValueSymbolTable.h" 41 #include "llvm/Pass.h" 42 #include "llvm/Support/Casting.h" 43 #include "llvm/Support/CodeGen.h" 44 #include "llvm/Support/Error.h" 45 #include "llvm/Support/MemoryBuffer.h" 46 #include "llvm/Support/Path.h" 47 #include "llvm/Support/RandomNumberGenerator.h" 48 #include "llvm/Support/VersionTuple.h" 49 #include <algorithm> 50 #include <cassert> 51 #include <cstdint> 52 #include <memory> 53 #include <utility> 54 #include <vector> 55 56 using namespace llvm; 57 58 //===----------------------------------------------------------------------===// 59 // Methods to implement the globals and functions lists. 60 // 61 62 // Explicit instantiations of SymbolTableListTraits since some of the methods 63 // are not in the public header file. 64 template class llvm::SymbolTableListTraits<Function>; 65 template class llvm::SymbolTableListTraits<GlobalVariable>; 66 template class llvm::SymbolTableListTraits<GlobalAlias>; 67 template class llvm::SymbolTableListTraits<GlobalIFunc>; 68 69 //===----------------------------------------------------------------------===// 70 // Primitive Module methods. 71 // 72 73 Module::Module(StringRef MID, LLVMContext &C) 74 : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>()), 75 Materializer(), ModuleID(std::string(MID)), 76 SourceFileName(std::string(MID)), DL("") { 77 Context.addModule(this); 78 } 79 80 Module::~Module() { 81 Context.removeModule(this); 82 dropAllReferences(); 83 GlobalList.clear(); 84 FunctionList.clear(); 85 AliasList.clear(); 86 IFuncList.clear(); 87 } 88 89 std::unique_ptr<RandomNumberGenerator> 90 Module::createRNG(const StringRef Name) const { 91 SmallString<32> Salt(Name); 92 93 // This RNG is guaranteed to produce the same random stream only 94 // when the Module ID and thus the input filename is the same. This 95 // might be problematic if the input filename extension changes 96 // (e.g. from .c to .bc or .ll). 97 // 98 // We could store this salt in NamedMetadata, but this would make 99 // the parameter non-const. This would unfortunately make this 100 // interface unusable by any Machine passes, since they only have a 101 // const reference to their IR Module. Alternatively we can always 102 // store salt metadata from the Module constructor. 103 Salt += sys::path::filename(getModuleIdentifier()); 104 105 return std::unique_ptr<RandomNumberGenerator>( 106 new RandomNumberGenerator(Salt)); 107 } 108 109 /// getNamedValue - Return the first global value in the module with 110 /// the specified name, of arbitrary type. This method returns null 111 /// if a global with the specified name is not found. 112 GlobalValue *Module::getNamedValue(StringRef Name) const { 113 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name)); 114 } 115 116 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 117 /// This ID is uniqued across modules in the current LLVMContext. 118 unsigned Module::getMDKindID(StringRef Name) const { 119 return Context.getMDKindID(Name); 120 } 121 122 /// getMDKindNames - Populate client supplied SmallVector with the name for 123 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 124 /// so it is filled in as an empty string. 125 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 126 return Context.getMDKindNames(Result); 127 } 128 129 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const { 130 return Context.getOperandBundleTags(Result); 131 } 132 133 //===----------------------------------------------------------------------===// 134 // Methods for easy access to the functions in the module. 135 // 136 137 // getOrInsertFunction - Look up the specified function in the module symbol 138 // table. If it does not exist, add a prototype for the function and return 139 // it. This is nice because it allows most passes to get away with not handling 140 // the symbol table directly for this common task. 141 // 142 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty, 143 AttributeList AttributeList) { 144 // See if we have a definition for the specified function already. 145 GlobalValue *F = getNamedValue(Name); 146 if (!F) { 147 // Nope, add it 148 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, 149 DL.getProgramAddressSpace(), Name); 150 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 151 New->setAttributes(AttributeList); 152 FunctionList.push_back(New); 153 return {Ty, New}; // Return the new prototype. 154 } 155 156 // If the function exists but has the wrong type, return a bitcast to the 157 // right type. 158 auto *PTy = PointerType::get(Ty, F->getAddressSpace()); 159 if (F->getType() != PTy) 160 return {Ty, ConstantExpr::getBitCast(F, PTy)}; 161 162 // Otherwise, we just found the existing function or a prototype. 163 return {Ty, F}; 164 } 165 166 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) { 167 return getOrInsertFunction(Name, Ty, AttributeList()); 168 } 169 170 // getFunction - Look up the specified function in the module symbol table. 171 // If it does not exist, return null. 172 // 173 Function *Module::getFunction(StringRef Name) const { 174 return dyn_cast_or_null<Function>(getNamedValue(Name)); 175 } 176 177 //===----------------------------------------------------------------------===// 178 // Methods for easy access to the global variables in the module. 179 // 180 181 /// getGlobalVariable - Look up the specified global variable in the module 182 /// symbol table. If it does not exist, return null. The type argument 183 /// should be the underlying type of the global, i.e., it should not have 184 /// the top-level PointerType, which represents the address of the global. 185 /// If AllowLocal is set to true, this function will return types that 186 /// have an local. By default, these types are not returned. 187 /// 188 GlobalVariable *Module::getGlobalVariable(StringRef Name, 189 bool AllowLocal) const { 190 if (GlobalVariable *Result = 191 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 192 if (AllowLocal || !Result->hasLocalLinkage()) 193 return Result; 194 return nullptr; 195 } 196 197 /// getOrInsertGlobal - Look up the specified global in the module symbol table. 198 /// 1. If it does not exist, add a declaration of the global and return it. 199 /// 2. Else, the global exists but has the wrong type: return the function 200 /// with a constantexpr cast to the right type. 201 /// 3. Finally, if the existing global is the correct declaration, return the 202 /// existing global. 203 Constant *Module::getOrInsertGlobal( 204 StringRef Name, Type *Ty, 205 function_ref<GlobalVariable *()> CreateGlobalCallback) { 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) 209 GV = CreateGlobalCallback(); 210 assert(GV && "The CreateGlobalCallback is expected to create a global"); 211 212 // If the variable exists but has the wrong type, return a bitcast to the 213 // right type. 214 Type *GVTy = GV->getType(); 215 PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace()); 216 if (GVTy != PTy) 217 return ConstantExpr::getBitCast(GV, PTy); 218 219 // Otherwise, we just found the existing function or a prototype. 220 return GV; 221 } 222 223 // Overload to construct a global variable using its constructor's defaults. 224 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 225 return getOrInsertGlobal(Name, Ty, [&] { 226 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 227 nullptr, Name); 228 }); 229 } 230 231 //===----------------------------------------------------------------------===// 232 // Methods for easy access to the global variables in the module. 233 // 234 235 // getNamedAlias - Look up the specified global in the module symbol table. 236 // If it does not exist, return null. 237 // 238 GlobalAlias *Module::getNamedAlias(StringRef Name) const { 239 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 240 } 241 242 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const { 243 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name)); 244 } 245 246 /// getNamedMetadata - Return the first NamedMDNode in the module with the 247 /// specified name. This method returns null if a NamedMDNode with the 248 /// specified name is not found. 249 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const { 250 SmallString<256> NameData; 251 StringRef NameRef = Name.toStringRef(NameData); 252 return NamedMDSymTab.lookup(NameRef); 253 } 254 255 /// getOrInsertNamedMetadata - Return the first named MDNode in the module 256 /// with the specified name. This method returns a new NamedMDNode if a 257 /// NamedMDNode with the specified name is not found. 258 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 259 NamedMDNode *&NMD = NamedMDSymTab[Name]; 260 if (!NMD) { 261 NMD = new NamedMDNode(Name); 262 NMD->setParent(this); 263 NamedMDList.push_back(NMD); 264 } 265 return NMD; 266 } 267 268 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and 269 /// delete it. 270 void Module::eraseNamedMetadata(NamedMDNode *NMD) { 271 NamedMDSymTab.erase(NMD->getName()); 272 NamedMDList.erase(NMD->getIterator()); 273 } 274 275 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) { 276 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) { 277 uint64_t Val = Behavior->getLimitedValue(); 278 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) { 279 MFB = static_cast<ModFlagBehavior>(Val); 280 return true; 281 } 282 } 283 return false; 284 } 285 286 bool Module::isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB, 287 MDString *&Key, Metadata *&Val) { 288 if (ModFlag.getNumOperands() < 3) 289 return false; 290 if (!isValidModFlagBehavior(ModFlag.getOperand(0), MFB)) 291 return false; 292 MDString *K = dyn_cast_or_null<MDString>(ModFlag.getOperand(1)); 293 if (!K) 294 return false; 295 Key = K; 296 Val = ModFlag.getOperand(2); 297 return true; 298 } 299 300 /// getModuleFlagsMetadata - Returns the module flags in the provided vector. 301 void Module:: 302 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 303 const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 304 if (!ModFlags) return; 305 306 for (const MDNode *Flag : ModFlags->operands()) { 307 ModFlagBehavior MFB; 308 MDString *Key = nullptr; 309 Metadata *Val = nullptr; 310 if (isValidModuleFlag(*Flag, MFB, Key, Val)) { 311 // Check the operands of the MDNode before accessing the operands. 312 // The verifier will actually catch these failures. 313 Flags.push_back(ModuleFlagEntry(MFB, Key, Val)); 314 } 315 } 316 } 317 318 /// Return the corresponding value if Key appears in module flags, otherwise 319 /// return null. 320 Metadata *Module::getModuleFlag(StringRef Key) const { 321 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 322 getModuleFlagsMetadata(ModuleFlags); 323 for (const ModuleFlagEntry &MFE : ModuleFlags) { 324 if (Key == MFE.Key->getString()) 325 return MFE.Val; 326 } 327 return nullptr; 328 } 329 330 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that 331 /// represents module-level flags. This method returns null if there are no 332 /// module-level flags. 333 NamedMDNode *Module::getModuleFlagsMetadata() const { 334 return getNamedMetadata("llvm.module.flags"); 335 } 336 337 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 338 /// represents module-level flags. If module-level flags aren't found, it 339 /// creates the named metadata that contains them. 340 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 341 return getOrInsertNamedMetadata("llvm.module.flags"); 342 } 343 344 /// addModuleFlag - Add a module-level flag to the module-level flags 345 /// metadata. It will create the module-level flags named metadata if it doesn't 346 /// already exist. 347 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 348 Metadata *Val) { 349 Type *Int32Ty = Type::getInt32Ty(Context); 350 Metadata *Ops[3] = { 351 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)), 352 MDString::get(Context, Key), Val}; 353 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 354 } 355 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 356 Constant *Val) { 357 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val)); 358 } 359 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 360 uint32_t Val) { 361 Type *Int32Ty = Type::getInt32Ty(Context); 362 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 363 } 364 void Module::addModuleFlag(MDNode *Node) { 365 assert(Node->getNumOperands() == 3 && 366 "Invalid number of operands for module flag!"); 367 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) && 368 isa<MDString>(Node->getOperand(1)) && 369 "Invalid operand types for module flag!"); 370 getOrInsertModuleFlagsMetadata()->addOperand(Node); 371 } 372 373 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key, 374 Metadata *Val) { 375 NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata(); 376 // Replace the flag if it already exists. 377 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) { 378 MDNode *Flag = ModFlags->getOperand(I); 379 ModFlagBehavior MFB; 380 MDString *K = nullptr; 381 Metadata *V = nullptr; 382 if (isValidModuleFlag(*Flag, MFB, K, V) && K->getString() == Key) { 383 Flag->replaceOperandWith(2, Val); 384 return; 385 } 386 } 387 addModuleFlag(Behavior, Key, Val); 388 } 389 390 void Module::setDataLayout(StringRef Desc) { 391 DL.reset(Desc); 392 } 393 394 void Module::setDataLayout(const DataLayout &Other) { DL = Other; } 395 396 const DataLayout &Module::getDataLayout() const { return DL; } 397 398 DICompileUnit *Module::debug_compile_units_iterator::operator*() const { 399 return cast<DICompileUnit>(CUs->getOperand(Idx)); 400 } 401 DICompileUnit *Module::debug_compile_units_iterator::operator->() const { 402 return cast<DICompileUnit>(CUs->getOperand(Idx)); 403 } 404 405 void Module::debug_compile_units_iterator::SkipNoDebugCUs() { 406 while (CUs && (Idx < CUs->getNumOperands()) && 407 ((*this)->getEmissionKind() == DICompileUnit::NoDebug)) 408 ++Idx; 409 } 410 411 iterator_range<Module::global_object_iterator> Module::global_objects() { 412 return concat<GlobalObject>(functions(), globals()); 413 } 414 iterator_range<Module::const_global_object_iterator> 415 Module::global_objects() const { 416 return concat<const GlobalObject>(functions(), globals()); 417 } 418 419 iterator_range<Module::global_value_iterator> Module::global_values() { 420 return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs()); 421 } 422 iterator_range<Module::const_global_value_iterator> 423 Module::global_values() const { 424 return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs()); 425 } 426 427 //===----------------------------------------------------------------------===// 428 // Methods to control the materialization of GlobalValues in the Module. 429 // 430 void Module::setMaterializer(GVMaterializer *GVM) { 431 assert(!Materializer && 432 "Module already has a GVMaterializer. Call materializeAll" 433 " to clear it out before setting another one."); 434 Materializer.reset(GVM); 435 } 436 437 Error Module::materialize(GlobalValue *GV) { 438 if (!Materializer) 439 return Error::success(); 440 441 return Materializer->materialize(GV); 442 } 443 444 Error Module::materializeAll() { 445 if (!Materializer) 446 return Error::success(); 447 std::unique_ptr<GVMaterializer> M = std::move(Materializer); 448 return M->materializeModule(); 449 } 450 451 Error Module::materializeMetadata() { 452 if (!Materializer) 453 return Error::success(); 454 return Materializer->materializeMetadata(); 455 } 456 457 //===----------------------------------------------------------------------===// 458 // Other module related stuff. 459 // 460 461 std::vector<StructType *> Module::getIdentifiedStructTypes() const { 462 // If we have a materializer, it is possible that some unread function 463 // uses a type that is currently not visible to a TypeFinder, so ask 464 // the materializer which types it created. 465 if (Materializer) 466 return Materializer->getIdentifiedStructTypes(); 467 468 std::vector<StructType *> Ret; 469 TypeFinder SrcStructTypes; 470 SrcStructTypes.run(*this, true); 471 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end()); 472 return Ret; 473 } 474 475 // dropAllReferences() - This function causes all the subelements to "let go" 476 // of all references that they are maintaining. This allows one to 'delete' a 477 // whole module at a time, even though there may be circular references... first 478 // all references are dropped, and all use counts go to zero. Then everything 479 // is deleted for real. Note that no operations are valid on an object that 480 // has "dropped all references", except operator delete. 481 // 482 void Module::dropAllReferences() { 483 for (Function &F : *this) 484 F.dropAllReferences(); 485 486 for (GlobalVariable &GV : globals()) 487 GV.dropAllReferences(); 488 489 for (GlobalAlias &GA : aliases()) 490 GA.dropAllReferences(); 491 492 for (GlobalIFunc &GIF : ifuncs()) 493 GIF.dropAllReferences(); 494 } 495 496 unsigned Module::getNumberRegisterParameters() const { 497 auto *Val = 498 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters")); 499 if (!Val) 500 return 0; 501 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 502 } 503 504 unsigned Module::getDwarfVersion() const { 505 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version")); 506 if (!Val) 507 return 0; 508 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 509 } 510 511 unsigned Module::getCodeViewFlag() const { 512 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView")); 513 if (!Val) 514 return 0; 515 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 516 } 517 518 unsigned Module::getInstructionCount() { 519 unsigned NumInstrs = 0; 520 for (Function &F : FunctionList) 521 NumInstrs += F.getInstructionCount(); 522 return NumInstrs; 523 } 524 525 Comdat *Module::getOrInsertComdat(StringRef Name) { 526 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first; 527 Entry.second.Name = &Entry; 528 return &Entry.second; 529 } 530 531 PICLevel::Level Module::getPICLevel() const { 532 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level")); 533 534 if (!Val) 535 return PICLevel::NotPIC; 536 537 return static_cast<PICLevel::Level>( 538 cast<ConstantInt>(Val->getValue())->getZExtValue()); 539 } 540 541 void Module::setPICLevel(PICLevel::Level PL) { 542 addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL); 543 } 544 545 PIELevel::Level Module::getPIELevel() const { 546 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level")); 547 548 if (!Val) 549 return PIELevel::Default; 550 551 return static_cast<PIELevel::Level>( 552 cast<ConstantInt>(Val->getValue())->getZExtValue()); 553 } 554 555 void Module::setPIELevel(PIELevel::Level PL) { 556 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL); 557 } 558 559 Optional<CodeModel::Model> Module::getCodeModel() const { 560 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model")); 561 562 if (!Val) 563 return None; 564 565 return static_cast<CodeModel::Model>( 566 cast<ConstantInt>(Val->getValue())->getZExtValue()); 567 } 568 569 void Module::setCodeModel(CodeModel::Model CL) { 570 // Linking object files with different code models is undefined behavior 571 // because the compiler would have to generate additional code (to span 572 // longer jumps) if a larger code model is used with a smaller one. 573 // Therefore we will treat attempts to mix code models as an error. 574 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL); 575 } 576 577 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) { 578 if (Kind == ProfileSummary::PSK_CSInstr) 579 setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M); 580 else 581 setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M); 582 } 583 584 Metadata *Module::getProfileSummary(bool IsCS) { 585 return (IsCS ? getModuleFlag("CSProfileSummary") 586 : getModuleFlag("ProfileSummary")); 587 } 588 589 bool Module::getSemanticInterposition() const { 590 Metadata *MF = getModuleFlag("SemanticInterposition"); 591 592 auto *Val = cast_or_null<ConstantAsMetadata>(MF); 593 if (!Val) 594 return false; 595 596 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 597 } 598 599 void Module::setSemanticInterposition(bool SI) { 600 addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI); 601 } 602 603 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) { 604 OwnedMemoryBuffer = std::move(MB); 605 } 606 607 bool Module::getRtLibUseGOT() const { 608 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT")); 609 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0); 610 } 611 612 void Module::setRtLibUseGOT() { 613 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1); 614 } 615 616 void Module::setSDKVersion(const VersionTuple &V) { 617 SmallVector<unsigned, 3> Entries; 618 Entries.push_back(V.getMajor()); 619 if (auto Minor = V.getMinor()) { 620 Entries.push_back(*Minor); 621 if (auto Subminor = V.getSubminor()) 622 Entries.push_back(*Subminor); 623 // Ignore the 'build' component as it can't be represented in the object 624 // file. 625 } 626 addModuleFlag(ModFlagBehavior::Warning, "SDK Version", 627 ConstantDataArray::get(Context, Entries)); 628 } 629 630 VersionTuple Module::getSDKVersion() const { 631 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version")); 632 if (!CM) 633 return {}; 634 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue()); 635 if (!Arr) 636 return {}; 637 auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> { 638 if (Index >= Arr->getNumElements()) 639 return None; 640 return (unsigned)Arr->getElementAsInteger(Index); 641 }; 642 auto Major = getVersionComponent(0); 643 if (!Major) 644 return {}; 645 VersionTuple Result = VersionTuple(*Major); 646 if (auto Minor = getVersionComponent(1)) { 647 Result = VersionTuple(*Major, *Minor); 648 if (auto Subminor = getVersionComponent(2)) { 649 Result = VersionTuple(*Major, *Minor, *Subminor); 650 } 651 } 652 return Result; 653 } 654 655 GlobalVariable *llvm::collectUsedGlobalVariables( 656 const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) { 657 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used"; 658 GlobalVariable *GV = M.getGlobalVariable(Name); 659 if (!GV || !GV->hasInitializer()) 660 return GV; 661 662 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 663 for (Value *Op : Init->operands()) { 664 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts()); 665 Set.insert(G); 666 } 667 return GV; 668 } 669