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