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