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