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/SmallString.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringMap.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/ADT/Twine.h" 20 #include "llvm/IR/Attributes.h" 21 #include "llvm/IR/Comdat.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DebugInfoMetadata.h" 25 #include "llvm/IR/DerivedTypes.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/GVMaterializer.h" 28 #include "llvm/IR/GlobalAlias.h" 29 #include "llvm/IR/GlobalIFunc.h" 30 #include "llvm/IR/GlobalValue.h" 31 #include "llvm/IR/GlobalVariable.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/IR/Metadata.h" 34 #include "llvm/IR/ModuleSummaryIndex.h" 35 #include "llvm/IR/SymbolTableListTraits.h" 36 #include "llvm/IR/Type.h" 37 #include "llvm/IR/TypeFinder.h" 38 #include "llvm/IR/Value.h" 39 #include "llvm/IR/ValueSymbolTable.h" 40 #include "llvm/Support/Casting.h" 41 #include "llvm/Support/CodeGen.h" 42 #include "llvm/Support/Error.h" 43 #include "llvm/Support/MemoryBuffer.h" 44 #include "llvm/Support/Path.h" 45 #include "llvm/Support/RandomNumberGenerator.h" 46 #include "llvm/Support/VersionTuple.h" 47 #include <cassert> 48 #include <cstdint> 49 #include <memory> 50 #include <optional> 51 #include <utility> 52 #include <vector> 53 54 using namespace llvm; 55 56 extern cl::opt<bool> UseNewDbgInfoFormat; 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>(-1)), 75 ModuleID(std::string(MID)), SourceFileName(std::string(MID)), 76 IsNewDbgInfoFormat(UseNewDbgInfoFormat) { 77 Context.addModule(this); 78 } 79 80 Module &Module::operator=(Module &&Other) { 81 assert(&Context == &Other.Context && "Module must be in the same Context"); 82 83 dropAllReferences(); 84 85 ModuleID = std::move(Other.ModuleID); 86 SourceFileName = std::move(Other.SourceFileName); 87 IsNewDbgInfoFormat = std::move(Other.IsNewDbgInfoFormat); 88 89 GlobalList.clear(); 90 GlobalList.splice(GlobalList.begin(), Other.GlobalList); 91 92 FunctionList.clear(); 93 FunctionList.splice(FunctionList.begin(), Other.FunctionList); 94 95 AliasList.clear(); 96 AliasList.splice(AliasList.begin(), Other.AliasList); 97 98 IFuncList.clear(); 99 IFuncList.splice(IFuncList.begin(), Other.IFuncList); 100 101 NamedMDList.clear(); 102 NamedMDList.splice(NamedMDList.begin(), Other.NamedMDList); 103 GlobalScopeAsm = std::move(Other.GlobalScopeAsm); 104 OwnedMemoryBuffer = std::move(Other.OwnedMemoryBuffer); 105 Materializer = std::move(Other.Materializer); 106 TargetTriple = std::move(Other.TargetTriple); 107 DL = std::move(Other.DL); 108 CurrentIntrinsicIds = std::move(Other.CurrentIntrinsicIds); 109 UniquedIntrinsicNames = std::move(Other.UniquedIntrinsicNames); 110 ModuleFlags = std::move(Other.ModuleFlags); 111 Context.addModule(this); 112 return *this; 113 } 114 115 Module::~Module() { 116 Context.removeModule(this); 117 dropAllReferences(); 118 GlobalList.clear(); 119 FunctionList.clear(); 120 AliasList.clear(); 121 IFuncList.clear(); 122 } 123 124 void Module::removeDebugIntrinsicDeclarations() { 125 auto *DeclareIntrinsicFn = 126 Intrinsic::getOrInsertDeclaration(this, Intrinsic::dbg_declare); 127 assert((!isMaterialized() || DeclareIntrinsicFn->hasZeroLiveUses()) && 128 "Debug declare intrinsic should have had uses removed."); 129 DeclareIntrinsicFn->eraseFromParent(); 130 auto *ValueIntrinsicFn = 131 Intrinsic::getOrInsertDeclaration(this, Intrinsic::dbg_value); 132 assert((!isMaterialized() || ValueIntrinsicFn->hasZeroLiveUses()) && 133 "Debug value intrinsic should have had uses removed."); 134 ValueIntrinsicFn->eraseFromParent(); 135 auto *AssignIntrinsicFn = 136 Intrinsic::getOrInsertDeclaration(this, Intrinsic::dbg_assign); 137 assert((!isMaterialized() || AssignIntrinsicFn->hasZeroLiveUses()) && 138 "Debug assign intrinsic should have had uses removed."); 139 AssignIntrinsicFn->eraseFromParent(); 140 auto *LabelntrinsicFn = 141 Intrinsic::getOrInsertDeclaration(this, Intrinsic::dbg_label); 142 assert((!isMaterialized() || LabelntrinsicFn->hasZeroLiveUses()) && 143 "Debug label intrinsic should have had uses removed."); 144 LabelntrinsicFn->eraseFromParent(); 145 } 146 147 std::unique_ptr<RandomNumberGenerator> 148 Module::createRNG(const StringRef Name) const { 149 SmallString<32> Salt(Name); 150 151 // This RNG is guaranteed to produce the same random stream only 152 // when the Module ID and thus the input filename is the same. This 153 // might be problematic if the input filename extension changes 154 // (e.g. from .c to .bc or .ll). 155 // 156 // We could store this salt in NamedMetadata, but this would make 157 // the parameter non-const. This would unfortunately make this 158 // interface unusable by any Machine passes, since they only have a 159 // const reference to their IR Module. Alternatively we can always 160 // store salt metadata from the Module constructor. 161 Salt += sys::path::filename(getModuleIdentifier()); 162 163 return std::unique_ptr<RandomNumberGenerator>( 164 new RandomNumberGenerator(Salt)); 165 } 166 167 /// getNamedValue - Return the first global value in the module with 168 /// the specified name, of arbitrary type. This method returns null 169 /// if a global with the specified name is not found. 170 GlobalValue *Module::getNamedValue(StringRef Name) const { 171 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name)); 172 } 173 174 unsigned Module::getNumNamedValues() const { 175 return getValueSymbolTable().size(); 176 } 177 178 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 179 /// This ID is uniqued across modules in the current LLVMContext. 180 unsigned Module::getMDKindID(StringRef Name) const { 181 return Context.getMDKindID(Name); 182 } 183 184 /// getMDKindNames - Populate client supplied SmallVector with the name for 185 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 186 /// so it is filled in as an empty string. 187 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 188 return Context.getMDKindNames(Result); 189 } 190 191 void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const { 192 return Context.getOperandBundleTags(Result); 193 } 194 195 //===----------------------------------------------------------------------===// 196 // Methods for easy access to the functions in the module. 197 // 198 199 // getOrInsertFunction - Look up the specified function in the module symbol 200 // table. If it does not exist, add a prototype for the function and return 201 // it. This is nice because it allows most passes to get away with not handling 202 // the symbol table directly for this common task. 203 // 204 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty, 205 AttributeList AttributeList) { 206 // See if we have a definition for the specified function already. 207 GlobalValue *F = getNamedValue(Name); 208 if (!F) { 209 // Nope, add it 210 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, 211 DL.getProgramAddressSpace(), Name, this); 212 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 213 New->setAttributes(AttributeList); 214 return {Ty, New}; // Return the new prototype. 215 } 216 217 // Otherwise, we just found the existing function or a prototype. 218 return {Ty, F}; 219 } 220 221 FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) { 222 return getOrInsertFunction(Name, Ty, AttributeList()); 223 } 224 225 // getFunction - Look up the specified function in the module symbol table. 226 // If it does not exist, return null. 227 // 228 Function *Module::getFunction(StringRef Name) const { 229 return dyn_cast_or_null<Function>(getNamedValue(Name)); 230 } 231 232 //===----------------------------------------------------------------------===// 233 // Methods for easy access to the global variables in the module. 234 // 235 236 /// getGlobalVariable - Look up the specified global variable in the module 237 /// symbol table. If it does not exist, return null. The type argument 238 /// should be the underlying type of the global, i.e., it should not have 239 /// the top-level PointerType, which represents the address of the global. 240 /// If AllowLocal is set to true, this function will return types that 241 /// have an local. By default, these types are not returned. 242 /// 243 GlobalVariable *Module::getGlobalVariable(StringRef Name, 244 bool AllowLocal) const { 245 if (GlobalVariable *Result = 246 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 247 if (AllowLocal || !Result->hasLocalLinkage()) 248 return Result; 249 return nullptr; 250 } 251 252 /// getOrInsertGlobal - Look up the specified global in the module symbol table. 253 /// 1. If it does not exist, add a declaration of the global and return it. 254 /// 2. Else, the global exists but has the wrong type: return the function 255 /// with a constantexpr cast to the right type. 256 /// 3. Finally, if the existing global is the correct declaration, return the 257 /// existing global. 258 Constant *Module::getOrInsertGlobal( 259 StringRef Name, Type *Ty, 260 function_ref<GlobalVariable *()> CreateGlobalCallback) { 261 // See if we have a definition for the specified global already. 262 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)); 263 if (!GV) 264 GV = CreateGlobalCallback(); 265 assert(GV && "The CreateGlobalCallback is expected to create a global"); 266 267 // Otherwise, we just found the existing function or a prototype. 268 return GV; 269 } 270 271 // Overload to construct a global variable using its constructor's defaults. 272 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 273 return getOrInsertGlobal(Name, Ty, [&] { 274 return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 275 nullptr, Name); 276 }); 277 } 278 279 //===----------------------------------------------------------------------===// 280 // Methods for easy access to the global variables in the module. 281 // 282 283 // getNamedAlias - Look up the specified global in the module symbol table. 284 // If it does not exist, return null. 285 // 286 GlobalAlias *Module::getNamedAlias(StringRef Name) const { 287 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 288 } 289 290 GlobalIFunc *Module::getNamedIFunc(StringRef Name) const { 291 return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name)); 292 } 293 294 /// getNamedMetadata - Return the first NamedMDNode in the module with the 295 /// specified name. This method returns null if a NamedMDNode with the 296 /// specified name is not found. 297 NamedMDNode *Module::getNamedMetadata(StringRef Name) const { 298 return NamedMDSymTab.lookup(Name); 299 } 300 301 /// getOrInsertNamedMetadata - Return the first named MDNode in the module 302 /// with the specified name. This method returns a new NamedMDNode if a 303 /// NamedMDNode with the specified name is not found. 304 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 305 NamedMDNode *&NMD = NamedMDSymTab[Name]; 306 if (!NMD) { 307 NMD = new NamedMDNode(Name); 308 NMD->setParent(this); 309 insertNamedMDNode(NMD); 310 if (Name == "llvm.module.flags") 311 ModuleFlags = NMD; 312 } 313 return NMD; 314 } 315 316 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and 317 /// delete it. 318 void Module::eraseNamedMetadata(NamedMDNode *NMD) { 319 NamedMDSymTab.erase(NMD->getName()); 320 if (NMD == ModuleFlags) 321 ModuleFlags = nullptr; 322 eraseNamedMDNode(NMD); 323 } 324 325 bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) { 326 if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) { 327 uint64_t Val = Behavior->getLimitedValue(); 328 if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) { 329 MFB = static_cast<ModFlagBehavior>(Val); 330 return true; 331 } 332 } 333 return false; 334 } 335 336 /// getModuleFlagsMetadata - Returns the module flags in the provided vector. 337 void Module:: 338 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 339 const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 340 if (!ModFlags) return; 341 342 for (const MDNode *Flag : ModFlags->operands()) { 343 // The verifier will catch errors, so no need to check them here. 344 auto *MFBConstant = mdconst::extract<ConstantInt>(Flag->getOperand(0)); 345 auto MFB = static_cast<ModFlagBehavior>(MFBConstant->getLimitedValue()); 346 MDString *Key = cast<MDString>(Flag->getOperand(1)); 347 Metadata *Val = Flag->getOperand(2); 348 Flags.push_back(ModuleFlagEntry(MFB, Key, Val)); 349 } 350 } 351 352 /// Return the corresponding value if Key appears in module flags, otherwise 353 /// return null. 354 Metadata *Module::getModuleFlag(StringRef Key) const { 355 const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 356 if (!ModFlags) 357 return nullptr; 358 for (const MDNode *Flag : ModFlags->operands()) { 359 if (Key == cast<MDString>(Flag->getOperand(1))->getString()) 360 return Flag->getOperand(2); 361 } 362 return nullptr; 363 } 364 365 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 366 /// represents module-level flags. If module-level flags aren't found, it 367 /// creates the named metadata that contains them. 368 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 369 if (ModuleFlags) 370 return ModuleFlags; 371 return getOrInsertNamedMetadata("llvm.module.flags"); 372 } 373 374 /// addModuleFlag - Add a module-level flag to the module-level flags 375 /// metadata. It will create the module-level flags named metadata if it doesn't 376 /// already exist. 377 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 378 Metadata *Val) { 379 Type *Int32Ty = Type::getInt32Ty(Context); 380 Metadata *Ops[3] = { 381 ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)), 382 MDString::get(Context, Key), Val}; 383 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 384 } 385 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 386 Constant *Val) { 387 addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val)); 388 } 389 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 390 uint32_t Val) { 391 Type *Int32Ty = Type::getInt32Ty(Context); 392 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 393 } 394 void Module::addModuleFlag(MDNode *Node) { 395 assert(Node->getNumOperands() == 3 && 396 "Invalid number of operands for module flag!"); 397 assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) && 398 isa<MDString>(Node->getOperand(1)) && 399 "Invalid operand types for module flag!"); 400 getOrInsertModuleFlagsMetadata()->addOperand(Node); 401 } 402 403 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key, 404 Metadata *Val) { 405 NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata(); 406 // Replace the flag if it already exists. 407 for (MDNode *Flag : ModFlags->operands()) { 408 if (cast<MDString>(Flag->getOperand(1))->getString() == Key) { 409 Flag->replaceOperandWith(2, Val); 410 return; 411 } 412 } 413 addModuleFlag(Behavior, Key, Val); 414 } 415 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key, 416 Constant *Val) { 417 setModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val)); 418 } 419 void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key, 420 uint32_t Val) { 421 Type *Int32Ty = Type::getInt32Ty(Context); 422 setModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 423 } 424 425 void Module::setDataLayout(StringRef Desc) { DL = DataLayout(Desc); } 426 427 void Module::setDataLayout(const DataLayout &Other) { DL = Other; } 428 429 DICompileUnit *Module::debug_compile_units_iterator::operator*() const { 430 return cast<DICompileUnit>(CUs->getOperand(Idx)); 431 } 432 DICompileUnit *Module::debug_compile_units_iterator::operator->() const { 433 return cast<DICompileUnit>(CUs->getOperand(Idx)); 434 } 435 436 void Module::debug_compile_units_iterator::SkipNoDebugCUs() { 437 while (CUs && (Idx < CUs->getNumOperands()) && 438 ((*this)->getEmissionKind() == DICompileUnit::NoDebug)) 439 ++Idx; 440 } 441 442 iterator_range<Module::global_object_iterator> Module::global_objects() { 443 return concat<GlobalObject>(functions(), globals()); 444 } 445 iterator_range<Module::const_global_object_iterator> 446 Module::global_objects() const { 447 return concat<const GlobalObject>(functions(), globals()); 448 } 449 450 iterator_range<Module::global_value_iterator> Module::global_values() { 451 return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs()); 452 } 453 iterator_range<Module::const_global_value_iterator> 454 Module::global_values() const { 455 return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs()); 456 } 457 458 //===----------------------------------------------------------------------===// 459 // Methods to control the materialization of GlobalValues in the Module. 460 // 461 void Module::setMaterializer(GVMaterializer *GVM) { 462 assert(!Materializer && 463 "Module already has a GVMaterializer. Call materializeAll" 464 " to clear it out before setting another one."); 465 Materializer.reset(GVM); 466 } 467 468 Error Module::materialize(GlobalValue *GV) { 469 if (!Materializer) 470 return Error::success(); 471 472 return Materializer->materialize(GV); 473 } 474 475 Error Module::materializeAll() { 476 if (!Materializer) 477 return Error::success(); 478 std::unique_ptr<GVMaterializer> M = std::move(Materializer); 479 return M->materializeModule(); 480 } 481 482 Error Module::materializeMetadata() { 483 if (!Materializer) 484 return Error::success(); 485 return Materializer->materializeMetadata(); 486 } 487 488 //===----------------------------------------------------------------------===// 489 // Other module related stuff. 490 // 491 492 std::vector<StructType *> Module::getIdentifiedStructTypes() const { 493 // If we have a materializer, it is possible that some unread function 494 // uses a type that is currently not visible to a TypeFinder, so ask 495 // the materializer which types it created. 496 if (Materializer) 497 return Materializer->getIdentifiedStructTypes(); 498 499 std::vector<StructType *> Ret; 500 TypeFinder SrcStructTypes; 501 SrcStructTypes.run(*this, true); 502 Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end()); 503 return Ret; 504 } 505 506 std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id, 507 const FunctionType *Proto) { 508 auto Encode = [&BaseName](unsigned Suffix) { 509 return (Twine(BaseName) + "." + Twine(Suffix)).str(); 510 }; 511 512 { 513 // fast path - the prototype is already known 514 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0}); 515 if (!UinItInserted.second) 516 return Encode(UinItInserted.first->second); 517 } 518 519 // Not known yet. A new entry was created with index 0. Check if there already 520 // exists a matching declaration, or select a new entry. 521 522 // Start looking for names with the current known maximum count (or 0). 523 auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0}); 524 unsigned Count = NiidItInserted.first->second; 525 526 // This might be slow if a whole population of intrinsics already existed, but 527 // we cache the values for later usage. 528 std::string NewName; 529 while (true) { 530 NewName = Encode(Count); 531 GlobalValue *F = getNamedValue(NewName); 532 if (!F) { 533 // Reserve this entry for the new proto 534 UniquedIntrinsicNames[{Id, Proto}] = Count; 535 break; 536 } 537 538 // A declaration with this name already exists. Remember it. 539 FunctionType *FT = dyn_cast<FunctionType>(F->getValueType()); 540 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count}); 541 if (FT == Proto) { 542 // It was a declaration for our prototype. This entry was allocated in the 543 // beginning. Update the count to match the existing declaration. 544 UinItInserted.first->second = Count; 545 break; 546 } 547 548 ++Count; 549 } 550 551 NiidItInserted.first->second = Count + 1; 552 553 return NewName; 554 } 555 556 // dropAllReferences() - This function causes all the subelements to "let go" 557 // of all references that they are maintaining. This allows one to 'delete' a 558 // whole module at a time, even though there may be circular references... first 559 // all references are dropped, and all use counts go to zero. Then everything 560 // is deleted for real. Note that no operations are valid on an object that 561 // has "dropped all references", except operator delete. 562 // 563 void Module::dropAllReferences() { 564 for (Function &F : *this) 565 F.dropAllReferences(); 566 567 for (GlobalVariable &GV : globals()) 568 GV.dropAllReferences(); 569 570 for (GlobalAlias &GA : aliases()) 571 GA.dropAllReferences(); 572 573 for (GlobalIFunc &GIF : ifuncs()) 574 GIF.dropAllReferences(); 575 } 576 577 unsigned Module::getNumberRegisterParameters() const { 578 auto *Val = 579 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters")); 580 if (!Val) 581 return 0; 582 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 583 } 584 585 unsigned Module::getDwarfVersion() const { 586 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version")); 587 if (!Val) 588 return 0; 589 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 590 } 591 592 bool Module::isDwarf64() const { 593 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64")); 594 return Val && cast<ConstantInt>(Val->getValue())->isOne(); 595 } 596 597 unsigned Module::getCodeViewFlag() const { 598 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView")); 599 if (!Val) 600 return 0; 601 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 602 } 603 604 unsigned Module::getInstructionCount() const { 605 unsigned NumInstrs = 0; 606 for (const Function &F : FunctionList) 607 NumInstrs += F.getInstructionCount(); 608 return NumInstrs; 609 } 610 611 Comdat *Module::getOrInsertComdat(StringRef Name) { 612 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first; 613 Entry.second.Name = &Entry; 614 return &Entry.second; 615 } 616 617 PICLevel::Level Module::getPICLevel() const { 618 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level")); 619 620 if (!Val) 621 return PICLevel::NotPIC; 622 623 return static_cast<PICLevel::Level>( 624 cast<ConstantInt>(Val->getValue())->getZExtValue()); 625 } 626 627 void Module::setPICLevel(PICLevel::Level PL) { 628 // The merge result of a non-PIC object and a PIC object can only be reliably 629 // used as a non-PIC object, so use the Min merge behavior. 630 addModuleFlag(ModFlagBehavior::Min, "PIC Level", PL); 631 } 632 633 PIELevel::Level Module::getPIELevel() const { 634 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level")); 635 636 if (!Val) 637 return PIELevel::Default; 638 639 return static_cast<PIELevel::Level>( 640 cast<ConstantInt>(Val->getValue())->getZExtValue()); 641 } 642 643 void Module::setPIELevel(PIELevel::Level PL) { 644 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL); 645 } 646 647 std::optional<CodeModel::Model> Module::getCodeModel() const { 648 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model")); 649 650 if (!Val) 651 return std::nullopt; 652 653 return static_cast<CodeModel::Model>( 654 cast<ConstantInt>(Val->getValue())->getZExtValue()); 655 } 656 657 void Module::setCodeModel(CodeModel::Model CL) { 658 // Linking object files with different code models is undefined behavior 659 // because the compiler would have to generate additional code (to span 660 // longer jumps) if a larger code model is used with a smaller one. 661 // Therefore we will treat attempts to mix code models as an error. 662 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL); 663 } 664 665 std::optional<uint64_t> Module::getLargeDataThreshold() const { 666 auto *Val = 667 cast_or_null<ConstantAsMetadata>(getModuleFlag("Large Data Threshold")); 668 669 if (!Val) 670 return std::nullopt; 671 672 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 673 } 674 675 void Module::setLargeDataThreshold(uint64_t Threshold) { 676 // Since the large data threshold goes along with the code model, the merge 677 // behavior is the same. 678 addModuleFlag(ModFlagBehavior::Error, "Large Data Threshold", 679 ConstantInt::get(Type::getInt64Ty(Context), Threshold)); 680 } 681 682 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) { 683 if (Kind == ProfileSummary::PSK_CSInstr) 684 setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M); 685 else 686 setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M); 687 } 688 689 Metadata *Module::getProfileSummary(bool IsCS) const { 690 return (IsCS ? getModuleFlag("CSProfileSummary") 691 : getModuleFlag("ProfileSummary")); 692 } 693 694 bool Module::getSemanticInterposition() const { 695 Metadata *MF = getModuleFlag("SemanticInterposition"); 696 697 auto *Val = cast_or_null<ConstantAsMetadata>(MF); 698 if (!Val) 699 return false; 700 701 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 702 } 703 704 void Module::setSemanticInterposition(bool SI) { 705 addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI); 706 } 707 708 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) { 709 OwnedMemoryBuffer = std::move(MB); 710 } 711 712 bool Module::getRtLibUseGOT() const { 713 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT")); 714 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0); 715 } 716 717 void Module::setRtLibUseGOT() { 718 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1); 719 } 720 721 bool Module::getDirectAccessExternalData() const { 722 auto *Val = cast_or_null<ConstantAsMetadata>( 723 getModuleFlag("direct-access-external-data")); 724 if (Val) 725 return cast<ConstantInt>(Val->getValue())->getZExtValue() > 0; 726 return getPICLevel() == PICLevel::NotPIC; 727 } 728 729 void Module::setDirectAccessExternalData(bool Value) { 730 addModuleFlag(ModFlagBehavior::Max, "direct-access-external-data", Value); 731 } 732 733 UWTableKind Module::getUwtable() const { 734 if (auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable"))) 735 return UWTableKind(cast<ConstantInt>(Val->getValue())->getZExtValue()); 736 return UWTableKind::None; 737 } 738 739 void Module::setUwtable(UWTableKind Kind) { 740 addModuleFlag(ModFlagBehavior::Max, "uwtable", uint32_t(Kind)); 741 } 742 743 FramePointerKind Module::getFramePointer() const { 744 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer")); 745 return static_cast<FramePointerKind>( 746 Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0); 747 } 748 749 void Module::setFramePointer(FramePointerKind Kind) { 750 addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind)); 751 } 752 753 StringRef Module::getStackProtectorGuard() const { 754 Metadata *MD = getModuleFlag("stack-protector-guard"); 755 if (auto *MDS = dyn_cast_or_null<MDString>(MD)) 756 return MDS->getString(); 757 return {}; 758 } 759 760 void Module::setStackProtectorGuard(StringRef Kind) { 761 MDString *ID = MDString::get(getContext(), Kind); 762 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID); 763 } 764 765 StringRef Module::getStackProtectorGuardReg() const { 766 Metadata *MD = getModuleFlag("stack-protector-guard-reg"); 767 if (auto *MDS = dyn_cast_or_null<MDString>(MD)) 768 return MDS->getString(); 769 return {}; 770 } 771 772 void Module::setStackProtectorGuardReg(StringRef Reg) { 773 MDString *ID = MDString::get(getContext(), Reg); 774 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID); 775 } 776 777 StringRef Module::getStackProtectorGuardSymbol() const { 778 Metadata *MD = getModuleFlag("stack-protector-guard-symbol"); 779 if (auto *MDS = dyn_cast_or_null<MDString>(MD)) 780 return MDS->getString(); 781 return {}; 782 } 783 784 void Module::setStackProtectorGuardSymbol(StringRef Symbol) { 785 MDString *ID = MDString::get(getContext(), Symbol); 786 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-symbol", ID); 787 } 788 789 int Module::getStackProtectorGuardOffset() const { 790 Metadata *MD = getModuleFlag("stack-protector-guard-offset"); 791 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD)) 792 return CI->getSExtValue(); 793 return INT_MAX; 794 } 795 796 void Module::setStackProtectorGuardOffset(int Offset) { 797 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset); 798 } 799 800 unsigned Module::getOverrideStackAlignment() const { 801 Metadata *MD = getModuleFlag("override-stack-alignment"); 802 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD)) 803 return CI->getZExtValue(); 804 return 0; 805 } 806 807 unsigned Module::getMaxTLSAlignment() const { 808 Metadata *MD = getModuleFlag("MaxTLSAlign"); 809 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD)) 810 return CI->getZExtValue(); 811 return 0; 812 } 813 814 void Module::setOverrideStackAlignment(unsigned Align) { 815 addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align); 816 } 817 818 static void addSDKVersionMD(const VersionTuple &V, Module &M, StringRef Name) { 819 SmallVector<unsigned, 3> Entries; 820 Entries.push_back(V.getMajor()); 821 if (auto Minor = V.getMinor()) { 822 Entries.push_back(*Minor); 823 if (auto Subminor = V.getSubminor()) 824 Entries.push_back(*Subminor); 825 // Ignore the 'build' component as it can't be represented in the object 826 // file. 827 } 828 M.addModuleFlag(Module::ModFlagBehavior::Warning, Name, 829 ConstantDataArray::get(M.getContext(), Entries)); 830 } 831 832 void Module::setSDKVersion(const VersionTuple &V) { 833 addSDKVersionMD(V, *this, "SDK Version"); 834 } 835 836 static VersionTuple getSDKVersionMD(Metadata *MD) { 837 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD); 838 if (!CM) 839 return {}; 840 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue()); 841 if (!Arr) 842 return {}; 843 auto getVersionComponent = [&](unsigned Index) -> std::optional<unsigned> { 844 if (Index >= Arr->getNumElements()) 845 return std::nullopt; 846 return (unsigned)Arr->getElementAsInteger(Index); 847 }; 848 auto Major = getVersionComponent(0); 849 if (!Major) 850 return {}; 851 VersionTuple Result = VersionTuple(*Major); 852 if (auto Minor = getVersionComponent(1)) { 853 Result = VersionTuple(*Major, *Minor); 854 if (auto Subminor = getVersionComponent(2)) { 855 Result = VersionTuple(*Major, *Minor, *Subminor); 856 } 857 } 858 return Result; 859 } 860 861 VersionTuple Module::getSDKVersion() const { 862 return getSDKVersionMD(getModuleFlag("SDK Version")); 863 } 864 865 GlobalVariable *llvm::collectUsedGlobalVariables( 866 const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) { 867 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used"; 868 GlobalVariable *GV = M.getGlobalVariable(Name); 869 if (!GV || !GV->hasInitializer()) 870 return GV; 871 872 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 873 for (Value *Op : Init->operands()) { 874 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts()); 875 Vec.push_back(G); 876 } 877 return GV; 878 } 879 880 void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) { 881 if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) { 882 std::unique_ptr<ProfileSummary> ProfileSummary( 883 ProfileSummary::getFromMD(SummaryMD)); 884 if (ProfileSummary) { 885 if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample || 886 !ProfileSummary->isPartialProfile()) 887 return; 888 uint64_t BlockCount = Index.getBlockCount(); 889 uint32_t NumCounts = ProfileSummary->getNumCounts(); 890 if (!NumCounts) 891 return; 892 double Ratio = (double)BlockCount / NumCounts; 893 ProfileSummary->setPartialProfileRatio(Ratio); 894 setProfileSummary(ProfileSummary->getMD(getContext()), 895 ProfileSummary::PSK_Sample); 896 } 897 } 898 } 899 900 StringRef Module::getDarwinTargetVariantTriple() const { 901 if (const auto *MD = getModuleFlag("darwin.target_variant.triple")) 902 return cast<MDString>(MD)->getString(); 903 return ""; 904 } 905 906 void Module::setDarwinTargetVariantTriple(StringRef T) { 907 addModuleFlag(ModFlagBehavior::Warning, "darwin.target_variant.triple", 908 MDString::get(getContext(), T)); 909 } 910 911 VersionTuple Module::getDarwinTargetVariantSDKVersion() const { 912 return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version")); 913 } 914 915 void Module::setDarwinTargetVariantSDKVersion(VersionTuple Version) { 916 addSDKVersionMD(Version, *this, "darwin.target_variant.SDK Version"); 917 } 918