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 std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id, 477 const FunctionType *Proto) { 478 auto Encode = [&BaseName](unsigned Suffix) { 479 return (Twine(BaseName) + "." + Twine(Suffix)).str(); 480 }; 481 482 { 483 // fast path - the prototype is already known 484 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0}); 485 if (!UinItInserted.second) 486 return Encode(UinItInserted.first->second); 487 } 488 489 // Not known yet. A new entry was created with index 0. Check if there already 490 // exists a matching declaration, or select a new entry. 491 492 // Start looking for names with the current known maximum count (or 0). 493 auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0}); 494 unsigned Count = NiidItInserted.first->second; 495 496 // This might be slow if a whole population of intrinsics already existed, but 497 // we cache the values for later usage. 498 std::string NewName; 499 while (true) { 500 NewName = Encode(Count); 501 GlobalValue *F = getNamedValue(NewName); 502 if (!F) { 503 // Reserve this entry for the new proto 504 UniquedIntrinsicNames[{Id, Proto}] = Count; 505 break; 506 } 507 508 // A declaration with this name already exists. Remember it. 509 FunctionType *FT = dyn_cast<FunctionType>(F->getType()->getElementType()); 510 auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count}); 511 if (FT == Proto) { 512 // It was a declaration for our prototype. This entry was allocated in the 513 // beginning. Update the count to match the existing declaration. 514 UinItInserted.first->second = Count; 515 break; 516 } 517 518 ++Count; 519 } 520 521 NiidItInserted.first->second = Count + 1; 522 523 return NewName; 524 } 525 526 // dropAllReferences() - This function causes all the subelements to "let go" 527 // of all references that they are maintaining. This allows one to 'delete' a 528 // whole module at a time, even though there may be circular references... first 529 // all references are dropped, and all use counts go to zero. Then everything 530 // is deleted for real. Note that no operations are valid on an object that 531 // has "dropped all references", except operator delete. 532 // 533 void Module::dropAllReferences() { 534 for (Function &F : *this) 535 F.dropAllReferences(); 536 537 for (GlobalVariable &GV : globals()) 538 GV.dropAllReferences(); 539 540 for (GlobalAlias &GA : aliases()) 541 GA.dropAllReferences(); 542 543 for (GlobalIFunc &GIF : ifuncs()) 544 GIF.dropAllReferences(); 545 } 546 547 unsigned Module::getNumberRegisterParameters() const { 548 auto *Val = 549 cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters")); 550 if (!Val) 551 return 0; 552 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 553 } 554 555 unsigned Module::getDwarfVersion() const { 556 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version")); 557 if (!Val) 558 return 0; 559 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 560 } 561 562 bool Module::isDwarf64() const { 563 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64")); 564 return Val && cast<ConstantInt>(Val->getValue())->isOne(); 565 } 566 567 unsigned Module::getCodeViewFlag() const { 568 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView")); 569 if (!Val) 570 return 0; 571 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 572 } 573 574 unsigned Module::getInstructionCount() const { 575 unsigned NumInstrs = 0; 576 for (const Function &F : FunctionList) 577 NumInstrs += F.getInstructionCount(); 578 return NumInstrs; 579 } 580 581 Comdat *Module::getOrInsertComdat(StringRef Name) { 582 auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first; 583 Entry.second.Name = &Entry; 584 return &Entry.second; 585 } 586 587 PICLevel::Level Module::getPICLevel() const { 588 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level")); 589 590 if (!Val) 591 return PICLevel::NotPIC; 592 593 return static_cast<PICLevel::Level>( 594 cast<ConstantInt>(Val->getValue())->getZExtValue()); 595 } 596 597 void Module::setPICLevel(PICLevel::Level PL) { 598 addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL); 599 } 600 601 PIELevel::Level Module::getPIELevel() const { 602 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level")); 603 604 if (!Val) 605 return PIELevel::Default; 606 607 return static_cast<PIELevel::Level>( 608 cast<ConstantInt>(Val->getValue())->getZExtValue()); 609 } 610 611 void Module::setPIELevel(PIELevel::Level PL) { 612 addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL); 613 } 614 615 Optional<CodeModel::Model> Module::getCodeModel() const { 616 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model")); 617 618 if (!Val) 619 return None; 620 621 return static_cast<CodeModel::Model>( 622 cast<ConstantInt>(Val->getValue())->getZExtValue()); 623 } 624 625 void Module::setCodeModel(CodeModel::Model CL) { 626 // Linking object files with different code models is undefined behavior 627 // because the compiler would have to generate additional code (to span 628 // longer jumps) if a larger code model is used with a smaller one. 629 // Therefore we will treat attempts to mix code models as an error. 630 addModuleFlag(ModFlagBehavior::Error, "Code Model", CL); 631 } 632 633 void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) { 634 if (Kind == ProfileSummary::PSK_CSInstr) 635 setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M); 636 else 637 setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M); 638 } 639 640 Metadata *Module::getProfileSummary(bool IsCS) const { 641 return (IsCS ? getModuleFlag("CSProfileSummary") 642 : getModuleFlag("ProfileSummary")); 643 } 644 645 bool Module::getSemanticInterposition() const { 646 Metadata *MF = getModuleFlag("SemanticInterposition"); 647 648 auto *Val = cast_or_null<ConstantAsMetadata>(MF); 649 if (!Val) 650 return false; 651 652 return cast<ConstantInt>(Val->getValue())->getZExtValue(); 653 } 654 655 void Module::setSemanticInterposition(bool SI) { 656 addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI); 657 } 658 659 void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) { 660 OwnedMemoryBuffer = std::move(MB); 661 } 662 663 bool Module::getRtLibUseGOT() const { 664 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT")); 665 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0); 666 } 667 668 void Module::setRtLibUseGOT() { 669 addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1); 670 } 671 672 bool Module::getUwtable() const { 673 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable")); 674 return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0); 675 } 676 677 void Module::setUwtable() { addModuleFlag(ModFlagBehavior::Max, "uwtable", 1); } 678 679 FramePointerKind Module::getFramePointer() const { 680 auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer")); 681 return static_cast<FramePointerKind>( 682 Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0); 683 } 684 685 void Module::setFramePointer(FramePointerKind Kind) { 686 addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind)); 687 } 688 689 StringRef Module::getStackProtectorGuard() const { 690 Metadata *MD = getModuleFlag("stack-protector-guard"); 691 if (auto *MDS = dyn_cast_or_null<MDString>(MD)) 692 return MDS->getString(); 693 return {}; 694 } 695 696 void Module::setStackProtectorGuard(StringRef Kind) { 697 MDString *ID = MDString::get(getContext(), Kind); 698 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID); 699 } 700 701 StringRef Module::getStackProtectorGuardReg() const { 702 Metadata *MD = getModuleFlag("stack-protector-guard-reg"); 703 if (auto *MDS = dyn_cast_or_null<MDString>(MD)) 704 return MDS->getString(); 705 return {}; 706 } 707 708 void Module::setStackProtectorGuardReg(StringRef Reg) { 709 MDString *ID = MDString::get(getContext(), Reg); 710 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID); 711 } 712 713 int Module::getStackProtectorGuardOffset() const { 714 Metadata *MD = getModuleFlag("stack-protector-guard-offset"); 715 if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD)) 716 return CI->getSExtValue(); 717 return INT_MAX; 718 } 719 720 void Module::setStackProtectorGuardOffset(int Offset) { 721 addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset); 722 } 723 724 void Module::setSDKVersion(const VersionTuple &V) { 725 SmallVector<unsigned, 3> Entries; 726 Entries.push_back(V.getMajor()); 727 if (auto Minor = V.getMinor()) { 728 Entries.push_back(*Minor); 729 if (auto Subminor = V.getSubminor()) 730 Entries.push_back(*Subminor); 731 // Ignore the 'build' component as it can't be represented in the object 732 // file. 733 } 734 addModuleFlag(ModFlagBehavior::Warning, "SDK Version", 735 ConstantDataArray::get(Context, Entries)); 736 } 737 738 VersionTuple Module::getSDKVersion() const { 739 auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version")); 740 if (!CM) 741 return {}; 742 auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue()); 743 if (!Arr) 744 return {}; 745 auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> { 746 if (Index >= Arr->getNumElements()) 747 return None; 748 return (unsigned)Arr->getElementAsInteger(Index); 749 }; 750 auto Major = getVersionComponent(0); 751 if (!Major) 752 return {}; 753 VersionTuple Result = VersionTuple(*Major); 754 if (auto Minor = getVersionComponent(1)) { 755 Result = VersionTuple(*Major, *Minor); 756 if (auto Subminor = getVersionComponent(2)) { 757 Result = VersionTuple(*Major, *Minor, *Subminor); 758 } 759 } 760 return Result; 761 } 762 763 GlobalVariable *llvm::collectUsedGlobalVariables( 764 const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) { 765 const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used"; 766 GlobalVariable *GV = M.getGlobalVariable(Name); 767 if (!GV || !GV->hasInitializer()) 768 return GV; 769 770 const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer()); 771 for (Value *Op : Init->operands()) { 772 GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts()); 773 Vec.push_back(G); 774 } 775 return GV; 776 } 777 778 void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) { 779 if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) { 780 std::unique_ptr<ProfileSummary> ProfileSummary( 781 ProfileSummary::getFromMD(SummaryMD)); 782 if (ProfileSummary) { 783 if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample || 784 !ProfileSummary->isPartialProfile()) 785 return; 786 uint64_t BlockCount = Index.getBlockCount(); 787 uint32_t NumCounts = ProfileSummary->getNumCounts(); 788 if (!NumCounts) 789 return; 790 double Ratio = (double)BlockCount / NumCounts; 791 ProfileSummary->setPartialProfileRatio(Ratio); 792 setProfileSummary(ProfileSummary->getMD(getContext()), 793 ProfileSummary::PSK_Sample); 794 } 795 } 796 } 797