1 //===- ModuleSummaryAnalysis.cpp - Module summary index builder -----------===// 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 pass builds a ModuleSummaryIndex object for the module, to be written 10 // to bitcode or LLVM assembly. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/DenseSet.h" 17 #include "llvm/ADT/MapVector.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/Analysis/BlockFrequencyInfo.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/IndirectCallPromotionAnalysis.h" 27 #include "llvm/Analysis/LoopInfo.h" 28 #include "llvm/Analysis/MemoryProfileInfo.h" 29 #include "llvm/Analysis/ProfileSummaryInfo.h" 30 #include "llvm/Analysis/StackSafetyAnalysis.h" 31 #include "llvm/Analysis/TypeMetadataUtils.h" 32 #include "llvm/IR/Attributes.h" 33 #include "llvm/IR/BasicBlock.h" 34 #include "llvm/IR/Constant.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/Dominators.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/IR/GlobalAlias.h" 39 #include "llvm/IR/GlobalValue.h" 40 #include "llvm/IR/GlobalVariable.h" 41 #include "llvm/IR/Instructions.h" 42 #include "llvm/IR/IntrinsicInst.h" 43 #include "llvm/IR/Metadata.h" 44 #include "llvm/IR/Module.h" 45 #include "llvm/IR/ModuleSummaryIndex.h" 46 #include "llvm/IR/Use.h" 47 #include "llvm/IR/User.h" 48 #include "llvm/InitializePasses.h" 49 #include "llvm/Object/ModuleSymbolTable.h" 50 #include "llvm/Object/SymbolicFile.h" 51 #include "llvm/Pass.h" 52 #include "llvm/Support/Casting.h" 53 #include "llvm/Support/CommandLine.h" 54 #include "llvm/Support/FileSystem.h" 55 #include <algorithm> 56 #include <cassert> 57 #include <cstdint> 58 #include <vector> 59 60 using namespace llvm; 61 using namespace llvm::memprof; 62 63 #define DEBUG_TYPE "module-summary-analysis" 64 65 // Option to force edges cold which will block importing when the 66 // -import-cold-multiplier is set to 0. Useful for debugging. 67 namespace llvm { 68 FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold = 69 FunctionSummary::FSHT_None; 70 } // namespace llvm 71 72 static cl::opt<FunctionSummary::ForceSummaryHotnessType, true> FSEC( 73 "force-summary-edges-cold", cl::Hidden, cl::location(ForceSummaryEdgesCold), 74 cl::desc("Force all edges in the function summary to cold"), 75 cl::values(clEnumValN(FunctionSummary::FSHT_None, "none", "None."), 76 clEnumValN(FunctionSummary::FSHT_AllNonCritical, 77 "all-non-critical", "All non-critical edges."), 78 clEnumValN(FunctionSummary::FSHT_All, "all", "All edges."))); 79 80 static cl::opt<std::string> ModuleSummaryDotFile( 81 "module-summary-dot-file", cl::Hidden, cl::value_desc("filename"), 82 cl::desc("File to emit dot graph of new summary into")); 83 84 static cl::opt<bool> EnableMemProfIndirectCallSupport( 85 "enable-memprof-indirect-call-support", cl::init(true), cl::Hidden, 86 cl::desc( 87 "Enable MemProf support for summarizing and cloning indirect calls")); 88 89 extern cl::opt<bool> ScalePartialSampleProfileWorkingSetSize; 90 91 extern cl::opt<unsigned> MaxNumVTableAnnotations; 92 93 extern cl::opt<bool> MemProfReportHintedSizes; 94 95 // Walk through the operands of a given User via worklist iteration and populate 96 // the set of GlobalValue references encountered. Invoked either on an 97 // Instruction or a GlobalVariable (which walks its initializer). 98 // Return true if any of the operands contains blockaddress. This is important 99 // to know when computing summary for global var, because if global variable 100 // references basic block address we can't import it separately from function 101 // containing that basic block. For simplicity we currently don't import such 102 // global vars at all. When importing function we aren't interested if any 103 // instruction in it takes an address of any basic block, because instruction 104 // can only take an address of basic block located in the same function. 105 // Set `RefLocalLinkageIFunc` to true if the analyzed value references a 106 // local-linkage ifunc. 107 static bool 108 findRefEdges(ModuleSummaryIndex &Index, const User *CurUser, 109 SetVector<ValueInfo, SmallVector<ValueInfo, 0>> &RefEdges, 110 SmallPtrSet<const User *, 8> &Visited, 111 bool &RefLocalLinkageIFunc) { 112 bool HasBlockAddress = false; 113 SmallVector<const User *, 32> Worklist; 114 if (Visited.insert(CurUser).second) 115 Worklist.push_back(CurUser); 116 117 while (!Worklist.empty()) { 118 const User *U = Worklist.pop_back_val(); 119 const auto *CB = dyn_cast<CallBase>(U); 120 121 for (const auto &OI : U->operands()) { 122 const User *Operand = dyn_cast<User>(OI); 123 if (!Operand) 124 continue; 125 if (isa<BlockAddress>(Operand)) { 126 HasBlockAddress = true; 127 continue; 128 } 129 if (auto *GV = dyn_cast<GlobalValue>(Operand)) { 130 // We have a reference to a global value. This should be added to 131 // the reference set unless it is a callee. Callees are handled 132 // specially by WriteFunction and are added to a separate list. 133 if (!(CB && CB->isCallee(&OI))) { 134 // If an ifunc has local linkage, do not add it into ref edges, and 135 // sets `RefLocalLinkageIFunc` to true. The referencer is not eligible 136 // for import. An ifunc doesn't have summary and ThinLTO cannot 137 // promote it; importing the referencer may cause linkage errors. 138 if (auto *GI = dyn_cast_if_present<GlobalIFunc>(GV); 139 GI && GI->hasLocalLinkage()) { 140 RefLocalLinkageIFunc = true; 141 continue; 142 } 143 RefEdges.insert(Index.getOrInsertValueInfo(GV)); 144 } 145 continue; 146 } 147 if (Visited.insert(Operand).second) 148 Worklist.push_back(Operand); 149 } 150 } 151 152 const Instruction *I = dyn_cast<Instruction>(CurUser); 153 if (I) { 154 uint64_t TotalCount = 0; 155 // MaxNumVTableAnnotations is the maximum number of vtables annotated on 156 // the instruction. 157 auto ValueDataArray = getValueProfDataFromInst( 158 *I, IPVK_VTableTarget, MaxNumVTableAnnotations, TotalCount); 159 160 for (const auto &V : ValueDataArray) 161 RefEdges.insert(Index.getOrInsertValueInfo(/* VTableGUID = */ 162 V.Value)); 163 } 164 return HasBlockAddress; 165 } 166 167 static CalleeInfo::HotnessType getHotness(uint64_t ProfileCount, 168 ProfileSummaryInfo *PSI) { 169 if (!PSI) 170 return CalleeInfo::HotnessType::Unknown; 171 if (PSI->isHotCount(ProfileCount)) 172 return CalleeInfo::HotnessType::Hot; 173 if (PSI->isColdCount(ProfileCount)) 174 return CalleeInfo::HotnessType::Cold; 175 return CalleeInfo::HotnessType::None; 176 } 177 178 static bool isNonRenamableLocal(const GlobalValue &GV) { 179 return GV.hasSection() && GV.hasLocalLinkage(); 180 } 181 182 /// Determine whether this call has all constant integer arguments (excluding 183 /// "this") and summarize it to VCalls or ConstVCalls as appropriate. 184 static void addVCallToSet( 185 DevirtCallSite Call, GlobalValue::GUID Guid, 186 SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>> 187 &VCalls, 188 SetVector<FunctionSummary::ConstVCall, 189 std::vector<FunctionSummary::ConstVCall>> &ConstVCalls) { 190 std::vector<uint64_t> Args; 191 // Start from the second argument to skip the "this" pointer. 192 for (auto &Arg : drop_begin(Call.CB.args())) { 193 auto *CI = dyn_cast<ConstantInt>(Arg); 194 if (!CI || CI->getBitWidth() > 64) { 195 VCalls.insert({Guid, Call.Offset}); 196 return; 197 } 198 Args.push_back(CI->getZExtValue()); 199 } 200 ConstVCalls.insert({{Guid, Call.Offset}, std::move(Args)}); 201 } 202 203 /// If this intrinsic call requires that we add information to the function 204 /// summary, do so via the non-constant reference arguments. 205 static void addIntrinsicToSummary( 206 const CallInst *CI, 207 SetVector<GlobalValue::GUID, std::vector<GlobalValue::GUID>> &TypeTests, 208 SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>> 209 &TypeTestAssumeVCalls, 210 SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>> 211 &TypeCheckedLoadVCalls, 212 SetVector<FunctionSummary::ConstVCall, 213 std::vector<FunctionSummary::ConstVCall>> 214 &TypeTestAssumeConstVCalls, 215 SetVector<FunctionSummary::ConstVCall, 216 std::vector<FunctionSummary::ConstVCall>> 217 &TypeCheckedLoadConstVCalls, 218 DominatorTree &DT) { 219 switch (CI->getCalledFunction()->getIntrinsicID()) { 220 case Intrinsic::type_test: 221 case Intrinsic::public_type_test: { 222 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1)); 223 auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata()); 224 if (!TypeId) 225 break; 226 GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString()); 227 228 // Produce a summary from type.test intrinsics. We only summarize type.test 229 // intrinsics that are used other than by an llvm.assume intrinsic. 230 // Intrinsics that are assumed are relevant only to the devirtualization 231 // pass, not the type test lowering pass. 232 bool HasNonAssumeUses = llvm::any_of(CI->uses(), [](const Use &CIU) { 233 return !isa<AssumeInst>(CIU.getUser()); 234 }); 235 if (HasNonAssumeUses) 236 TypeTests.insert(Guid); 237 238 SmallVector<DevirtCallSite, 4> DevirtCalls; 239 SmallVector<CallInst *, 4> Assumes; 240 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT); 241 for (auto &Call : DevirtCalls) 242 addVCallToSet(Call, Guid, TypeTestAssumeVCalls, 243 TypeTestAssumeConstVCalls); 244 245 break; 246 } 247 248 case Intrinsic::type_checked_load_relative: 249 case Intrinsic::type_checked_load: { 250 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(2)); 251 auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata()); 252 if (!TypeId) 253 break; 254 GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString()); 255 256 SmallVector<DevirtCallSite, 4> DevirtCalls; 257 SmallVector<Instruction *, 4> LoadedPtrs; 258 SmallVector<Instruction *, 4> Preds; 259 bool HasNonCallUses = false; 260 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds, 261 HasNonCallUses, CI, DT); 262 // Any non-call uses of the result of llvm.type.checked.load will 263 // prevent us from optimizing away the llvm.type.test. 264 if (HasNonCallUses) 265 TypeTests.insert(Guid); 266 for (auto &Call : DevirtCalls) 267 addVCallToSet(Call, Guid, TypeCheckedLoadVCalls, 268 TypeCheckedLoadConstVCalls); 269 270 break; 271 } 272 default: 273 break; 274 } 275 } 276 277 static bool isNonVolatileLoad(const Instruction *I) { 278 if (const auto *LI = dyn_cast<LoadInst>(I)) 279 return !LI->isVolatile(); 280 281 return false; 282 } 283 284 static bool isNonVolatileStore(const Instruction *I) { 285 if (const auto *SI = dyn_cast<StoreInst>(I)) 286 return !SI->isVolatile(); 287 288 return false; 289 } 290 291 // Returns true if the function definition must be unreachable. 292 // 293 // Note if this helper function returns true, `F` is guaranteed 294 // to be unreachable; if it returns false, `F` might still 295 // be unreachable but not covered by this helper function. 296 static bool mustBeUnreachableFunction(const Function &F) { 297 // A function must be unreachable if its entry block ends with an 298 // 'unreachable'. 299 assert(!F.isDeclaration()); 300 return isa<UnreachableInst>(F.getEntryBlock().getTerminator()); 301 } 302 303 static void computeFunctionSummary( 304 ModuleSummaryIndex &Index, const Module &M, const Function &F, 305 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, DominatorTree &DT, 306 bool HasLocalsInUsedOrAsm, DenseSet<GlobalValue::GUID> &CantBePromoted, 307 bool IsThinLTO, 308 std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback) { 309 // Summary not currently supported for anonymous functions, they should 310 // have been named. 311 assert(F.hasName()); 312 313 unsigned NumInsts = 0; 314 // Map from callee ValueId to profile count. Used to accumulate profile 315 // counts for all static calls to a given callee. 316 MapVector<ValueInfo, CalleeInfo, DenseMap<ValueInfo, unsigned>, 317 SmallVector<FunctionSummary::EdgeTy, 0>> 318 CallGraphEdges; 319 SetVector<ValueInfo, SmallVector<ValueInfo, 0>> RefEdges, LoadRefEdges, 320 StoreRefEdges; 321 SetVector<GlobalValue::GUID, std::vector<GlobalValue::GUID>> TypeTests; 322 SetVector<FunctionSummary::VFuncId, std::vector<FunctionSummary::VFuncId>> 323 TypeTestAssumeVCalls, TypeCheckedLoadVCalls; 324 SetVector<FunctionSummary::ConstVCall, 325 std::vector<FunctionSummary::ConstVCall>> 326 TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls; 327 ICallPromotionAnalysis ICallAnalysis; 328 SmallPtrSet<const User *, 8> Visited; 329 330 // Add personality function, prefix data and prologue data to function's ref 331 // list. 332 bool HasLocalIFuncCallOrRef = false; 333 findRefEdges(Index, &F, RefEdges, Visited, HasLocalIFuncCallOrRef); 334 std::vector<const Instruction *> NonVolatileLoads; 335 std::vector<const Instruction *> NonVolatileStores; 336 337 std::vector<CallsiteInfo> Callsites; 338 std::vector<AllocInfo> Allocs; 339 340 #ifndef NDEBUG 341 DenseSet<const CallBase *> CallsThatMayHaveMemprofSummary; 342 #endif 343 344 bool HasInlineAsmMaybeReferencingInternal = false; 345 bool HasIndirBranchToBlockAddress = false; 346 bool HasUnknownCall = false; 347 bool MayThrow = false; 348 for (const BasicBlock &BB : F) { 349 // We don't allow inlining of function with indirect branch to blockaddress. 350 // If the blockaddress escapes the function, e.g., via a global variable, 351 // inlining may lead to an invalid cross-function reference. So we shouldn't 352 // import such function either. 353 if (BB.hasAddressTaken()) { 354 for (User *U : BlockAddress::get(const_cast<BasicBlock *>(&BB))->users()) 355 if (!isa<CallBrInst>(*U)) { 356 HasIndirBranchToBlockAddress = true; 357 break; 358 } 359 } 360 361 for (const Instruction &I : BB) { 362 if (I.isDebugOrPseudoInst()) 363 continue; 364 ++NumInsts; 365 366 // Regular LTO module doesn't participate in ThinLTO import, 367 // so no reference from it can be read/writeonly, since this 368 // would require importing variable as local copy 369 if (IsThinLTO) { 370 if (isNonVolatileLoad(&I)) { 371 // Postpone processing of non-volatile load instructions 372 // See comments below 373 Visited.insert(&I); 374 NonVolatileLoads.push_back(&I); 375 continue; 376 } else if (isNonVolatileStore(&I)) { 377 Visited.insert(&I); 378 NonVolatileStores.push_back(&I); 379 // All references from second operand of store (destination address) 380 // can be considered write-only if they're not referenced by any 381 // non-store instruction. References from first operand of store 382 // (stored value) can't be treated either as read- or as write-only 383 // so we add them to RefEdges as we do with all other instructions 384 // except non-volatile load. 385 Value *Stored = I.getOperand(0); 386 if (auto *GV = dyn_cast<GlobalValue>(Stored)) 387 // findRefEdges will try to examine GV operands, so instead 388 // of calling it we should add GV to RefEdges directly. 389 RefEdges.insert(Index.getOrInsertValueInfo(GV)); 390 else if (auto *U = dyn_cast<User>(Stored)) 391 findRefEdges(Index, U, RefEdges, Visited, HasLocalIFuncCallOrRef); 392 continue; 393 } 394 } 395 findRefEdges(Index, &I, RefEdges, Visited, HasLocalIFuncCallOrRef); 396 const auto *CB = dyn_cast<CallBase>(&I); 397 if (!CB) { 398 if (I.mayThrow()) 399 MayThrow = true; 400 continue; 401 } 402 403 const auto *CI = dyn_cast<CallInst>(&I); 404 // Since we don't know exactly which local values are referenced in inline 405 // assembly, conservatively mark the function as possibly referencing 406 // a local value from inline assembly to ensure we don't export a 407 // reference (which would require renaming and promotion of the 408 // referenced value). 409 if (HasLocalsInUsedOrAsm && CI && CI->isInlineAsm()) 410 HasInlineAsmMaybeReferencingInternal = true; 411 412 // Compute this once per indirect call. 413 uint32_t NumCandidates = 0; 414 uint64_t TotalCount = 0; 415 MutableArrayRef<InstrProfValueData> CandidateProfileData; 416 417 auto *CalledValue = CB->getCalledOperand(); 418 auto *CalledFunction = CB->getCalledFunction(); 419 if (CalledValue && !CalledFunction) { 420 CalledValue = CalledValue->stripPointerCasts(); 421 // Stripping pointer casts can reveal a called function. 422 CalledFunction = dyn_cast<Function>(CalledValue); 423 } 424 // Check if this is an alias to a function. If so, get the 425 // called aliasee for the checks below. 426 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) { 427 assert(!CalledFunction && "Expected null called function in callsite for alias"); 428 CalledFunction = dyn_cast<Function>(GA->getAliaseeObject()); 429 } 430 // Check if this is a direct call to a known function or a known 431 // intrinsic, or an indirect call with profile data. 432 if (CalledFunction) { 433 if (CI && CalledFunction->isIntrinsic()) { 434 addIntrinsicToSummary( 435 CI, TypeTests, TypeTestAssumeVCalls, TypeCheckedLoadVCalls, 436 TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls, DT); 437 continue; 438 } 439 // We should have named any anonymous globals 440 assert(CalledFunction->hasName()); 441 auto ScaledCount = PSI->getProfileCount(*CB, BFI); 442 auto Hotness = ScaledCount ? getHotness(*ScaledCount, PSI) 443 : CalleeInfo::HotnessType::Unknown; 444 if (ForceSummaryEdgesCold != FunctionSummary::FSHT_None) 445 Hotness = CalleeInfo::HotnessType::Cold; 446 447 // Use the original CalledValue, in case it was an alias. We want 448 // to record the call edge to the alias in that case. Eventually 449 // an alias summary will be created to associate the alias and 450 // aliasee. 451 auto &ValueInfo = CallGraphEdges[Index.getOrInsertValueInfo( 452 cast<GlobalValue>(CalledValue))]; 453 ValueInfo.updateHotness(Hotness); 454 if (CB->isTailCall()) 455 ValueInfo.setHasTailCall(true); 456 // Add the relative block frequency to CalleeInfo if there is no profile 457 // information. 458 if (BFI != nullptr && Hotness == CalleeInfo::HotnessType::Unknown) { 459 uint64_t BBFreq = BFI->getBlockFreq(&BB).getFrequency(); 460 uint64_t EntryFreq = BFI->getEntryFreq().getFrequency(); 461 ValueInfo.updateRelBlockFreq(BBFreq, EntryFreq); 462 } 463 } else { 464 HasUnknownCall = true; 465 // If F is imported, a local linkage ifunc (e.g. target_clones on a 466 // static function) called by F will be cloned. Since summaries don't 467 // track ifunc, we do not know implementation functions referenced by 468 // the ifunc resolver need to be promoted in the exporter, and we will 469 // get linker errors due to cloned declarations for implementation 470 // functions. As a simple fix, just mark F as not eligible for import. 471 // Non-local ifunc is not cloned and does not have the issue. 472 if (auto *GI = dyn_cast_if_present<GlobalIFunc>(CalledValue)) 473 if (GI->hasLocalLinkage()) 474 HasLocalIFuncCallOrRef = true; 475 // Skip inline assembly calls. 476 if (CI && CI->isInlineAsm()) 477 continue; 478 // Skip direct calls. 479 if (!CalledValue || isa<Constant>(CalledValue)) 480 continue; 481 482 // Check if the instruction has a callees metadata. If so, add callees 483 // to CallGraphEdges to reflect the references from the metadata, and 484 // to enable importing for subsequent indirect call promotion and 485 // inlining. 486 if (auto *MD = I.getMetadata(LLVMContext::MD_callees)) { 487 for (const auto &Op : MD->operands()) { 488 Function *Callee = mdconst::extract_or_null<Function>(Op); 489 if (Callee) 490 CallGraphEdges[Index.getOrInsertValueInfo(Callee)]; 491 } 492 } 493 494 CandidateProfileData = 495 ICallAnalysis.getPromotionCandidatesForInstruction(&I, TotalCount, 496 NumCandidates); 497 for (const auto &Candidate : CandidateProfileData) 498 CallGraphEdges[Index.getOrInsertValueInfo(Candidate.Value)] 499 .updateHotness(getHotness(Candidate.Count, PSI)); 500 } 501 502 // Summarize memprof related metadata. This is only needed for ThinLTO. 503 if (!IsThinLTO) 504 continue; 505 506 // Skip indirect calls if we haven't enabled memprof ICP. 507 if (!CalledFunction && !EnableMemProfIndirectCallSupport) 508 continue; 509 510 // Ensure we keep this analysis in sync with the handling in the ThinLTO 511 // backend (see MemProfContextDisambiguation::applyImport). Save this call 512 // so that we can skip it in checking the reverse case later. 513 assert(mayHaveMemprofSummary(CB)); 514 #ifndef NDEBUG 515 CallsThatMayHaveMemprofSummary.insert(CB); 516 #endif 517 518 // Compute the list of stack ids first (so we can trim them from the stack 519 // ids on any MIBs). 520 CallStack<MDNode, MDNode::op_iterator> InstCallsite( 521 I.getMetadata(LLVMContext::MD_callsite)); 522 auto *MemProfMD = I.getMetadata(LLVMContext::MD_memprof); 523 if (MemProfMD) { 524 std::vector<MIBInfo> MIBs; 525 std::vector<uint64_t> TotalSizes; 526 for (auto &MDOp : MemProfMD->operands()) { 527 auto *MIBMD = cast<const MDNode>(MDOp); 528 MDNode *StackNode = getMIBStackNode(MIBMD); 529 assert(StackNode); 530 SmallVector<unsigned> StackIdIndices; 531 CallStack<MDNode, MDNode::op_iterator> StackContext(StackNode); 532 // Collapse out any on the allocation call (inlining). 533 for (auto ContextIter = 534 StackContext.beginAfterSharedPrefix(InstCallsite); 535 ContextIter != StackContext.end(); ++ContextIter) { 536 unsigned StackIdIdx = Index.addOrGetStackIdIndex(*ContextIter); 537 // If this is a direct recursion, simply skip the duplicate 538 // entries. If this is mutual recursion, handling is left to 539 // the LTO link analysis client. 540 if (StackIdIndices.empty() || StackIdIndices.back() != StackIdIdx) 541 StackIdIndices.push_back(StackIdIdx); 542 } 543 MIBs.push_back( 544 MIBInfo(getMIBAllocType(MIBMD), std::move(StackIdIndices))); 545 if (MemProfReportHintedSizes) { 546 auto TotalSize = getMIBTotalSize(MIBMD); 547 assert(TotalSize); 548 TotalSizes.push_back(TotalSize); 549 } 550 } 551 Allocs.push_back(AllocInfo(std::move(MIBs))); 552 if (MemProfReportHintedSizes) { 553 assert(Allocs.back().MIBs.size() == TotalSizes.size()); 554 Allocs.back().TotalSizes = std::move(TotalSizes); 555 } 556 } else if (!InstCallsite.empty()) { 557 SmallVector<unsigned> StackIdIndices; 558 for (auto StackId : InstCallsite) 559 StackIdIndices.push_back(Index.addOrGetStackIdIndex(StackId)); 560 if (CalledFunction) { 561 // Use the original CalledValue, in case it was an alias. We want 562 // to record the call edge to the alias in that case. Eventually 563 // an alias summary will be created to associate the alias and 564 // aliasee. 565 auto CalleeValueInfo = 566 Index.getOrInsertValueInfo(cast<GlobalValue>(CalledValue)); 567 Callsites.push_back({CalleeValueInfo, StackIdIndices}); 568 } else { 569 assert(EnableMemProfIndirectCallSupport); 570 // For indirect callsites, create multiple Callsites, one per target. 571 // This enables having a different set of clone versions per target, 572 // and we will apply the cloning decisions while speculatively 573 // devirtualizing in the ThinLTO backends. 574 for (const auto &Candidate : CandidateProfileData) { 575 auto CalleeValueInfo = Index.getOrInsertValueInfo(Candidate.Value); 576 Callsites.push_back({CalleeValueInfo, StackIdIndices}); 577 } 578 } 579 } 580 } 581 } 582 583 if (PSI->hasPartialSampleProfile() && ScalePartialSampleProfileWorkingSetSize) 584 Index.addBlockCount(F.size()); 585 586 SmallVector<ValueInfo, 0> Refs; 587 if (IsThinLTO) { 588 auto AddRefEdges = 589 [&](const std::vector<const Instruction *> &Instrs, 590 SetVector<ValueInfo, SmallVector<ValueInfo, 0>> &Edges, 591 SmallPtrSet<const User *, 8> &Cache) { 592 for (const auto *I : Instrs) { 593 Cache.erase(I); 594 findRefEdges(Index, I, Edges, Cache, HasLocalIFuncCallOrRef); 595 } 596 }; 597 598 // By now we processed all instructions in a function, except 599 // non-volatile loads and non-volatile value stores. Let's find 600 // ref edges for both of instruction sets 601 AddRefEdges(NonVolatileLoads, LoadRefEdges, Visited); 602 // We can add some values to the Visited set when processing load 603 // instructions which are also used by stores in NonVolatileStores. 604 // For example this can happen if we have following code: 605 // 606 // store %Derived* @foo, %Derived** bitcast (%Base** @bar to %Derived**) 607 // %42 = load %Derived*, %Derived** bitcast (%Base** @bar to %Derived**) 608 // 609 // After processing loads we'll add bitcast to the Visited set, and if 610 // we use the same set while processing stores, we'll never see store 611 // to @bar and @bar will be mistakenly treated as readonly. 612 SmallPtrSet<const llvm::User *, 8> StoreCache; 613 AddRefEdges(NonVolatileStores, StoreRefEdges, StoreCache); 614 615 // If both load and store instruction reference the same variable 616 // we won't be able to optimize it. Add all such reference edges 617 // to RefEdges set. 618 for (const auto &VI : StoreRefEdges) 619 if (LoadRefEdges.remove(VI)) 620 RefEdges.insert(VI); 621 622 unsigned RefCnt = RefEdges.size(); 623 // All new reference edges inserted in two loops below are either 624 // read or write only. They will be grouped in the end of RefEdges 625 // vector, so we can use a single integer value to identify them. 626 for (const auto &VI : LoadRefEdges) 627 RefEdges.insert(VI); 628 629 unsigned FirstWORef = RefEdges.size(); 630 for (const auto &VI : StoreRefEdges) 631 RefEdges.insert(VI); 632 633 Refs = RefEdges.takeVector(); 634 for (; RefCnt < FirstWORef; ++RefCnt) 635 Refs[RefCnt].setReadOnly(); 636 637 for (; RefCnt < Refs.size(); ++RefCnt) 638 Refs[RefCnt].setWriteOnly(); 639 } else { 640 Refs = RefEdges.takeVector(); 641 } 642 // Explicit add hot edges to enforce importing for designated GUIDs for 643 // sample PGO, to enable the same inlines as the profiled optimized binary. 644 for (auto &I : F.getImportGUIDs()) 645 CallGraphEdges[Index.getOrInsertValueInfo(I)].updateHotness( 646 ForceSummaryEdgesCold == FunctionSummary::FSHT_All 647 ? CalleeInfo::HotnessType::Cold 648 : CalleeInfo::HotnessType::Critical); 649 650 #ifndef NDEBUG 651 // Make sure that all calls we decided could not have memprof summaries get a 652 // false value for mayHaveMemprofSummary, to ensure that this handling remains 653 // in sync with the ThinLTO backend handling. 654 if (IsThinLTO) { 655 for (const BasicBlock &BB : F) { 656 for (const Instruction &I : BB) { 657 const auto *CB = dyn_cast<CallBase>(&I); 658 if (!CB) 659 continue; 660 // We already checked these above. 661 if (CallsThatMayHaveMemprofSummary.count(CB)) 662 continue; 663 assert(!mayHaveMemprofSummary(CB)); 664 } 665 } 666 } 667 #endif 668 669 bool NonRenamableLocal = isNonRenamableLocal(F); 670 bool NotEligibleForImport = 671 NonRenamableLocal || HasInlineAsmMaybeReferencingInternal || 672 HasIndirBranchToBlockAddress || HasLocalIFuncCallOrRef; 673 GlobalValueSummary::GVFlags Flags( 674 F.getLinkage(), F.getVisibility(), NotEligibleForImport, 675 /* Live = */ false, F.isDSOLocal(), F.canBeOmittedFromSymbolTable(), 676 GlobalValueSummary::ImportKind::Definition); 677 FunctionSummary::FFlags FunFlags{ 678 F.doesNotAccessMemory(), F.onlyReadsMemory() && !F.doesNotAccessMemory(), 679 F.hasFnAttribute(Attribute::NoRecurse), F.returnDoesNotAlias(), 680 // FIXME: refactor this to use the same code that inliner is using. 681 // Don't try to import functions with noinline attribute. 682 F.getAttributes().hasFnAttr(Attribute::NoInline), 683 F.hasFnAttribute(Attribute::AlwaysInline), 684 F.hasFnAttribute(Attribute::NoUnwind), MayThrow, HasUnknownCall, 685 mustBeUnreachableFunction(F)}; 686 std::vector<FunctionSummary::ParamAccess> ParamAccesses; 687 if (auto *SSI = GetSSICallback(F)) 688 ParamAccesses = SSI->getParamAccesses(Index); 689 auto FuncSummary = std::make_unique<FunctionSummary>( 690 Flags, NumInsts, FunFlags, std::move(Refs), CallGraphEdges.takeVector(), 691 TypeTests.takeVector(), TypeTestAssumeVCalls.takeVector(), 692 TypeCheckedLoadVCalls.takeVector(), 693 TypeTestAssumeConstVCalls.takeVector(), 694 TypeCheckedLoadConstVCalls.takeVector(), std::move(ParamAccesses), 695 std::move(Callsites), std::move(Allocs)); 696 if (NonRenamableLocal) 697 CantBePromoted.insert(F.getGUID()); 698 Index.addGlobalValueSummary(F, std::move(FuncSummary)); 699 } 700 701 /// Find function pointers referenced within the given vtable initializer 702 /// (or subset of an initializer) \p I. The starting offset of \p I within 703 /// the vtable initializer is \p StartingOffset. Any discovered function 704 /// pointers are added to \p VTableFuncs along with their cumulative offset 705 /// within the initializer. 706 static void findFuncPointers(const Constant *I, uint64_t StartingOffset, 707 const Module &M, ModuleSummaryIndex &Index, 708 VTableFuncList &VTableFuncs, 709 const GlobalVariable &OrigGV) { 710 // First check if this is a function pointer. 711 if (I->getType()->isPointerTy()) { 712 auto C = I->stripPointerCasts(); 713 auto A = dyn_cast<GlobalAlias>(C); 714 if (isa<Function>(C) || (A && isa<Function>(A->getAliasee()))) { 715 auto GV = dyn_cast<GlobalValue>(C); 716 assert(GV); 717 // We can disregard __cxa_pure_virtual as a possible call target, as 718 // calls to pure virtuals are UB. 719 if (GV && GV->getName() != "__cxa_pure_virtual") 720 VTableFuncs.push_back({Index.getOrInsertValueInfo(GV), StartingOffset}); 721 return; 722 } 723 } 724 725 // Walk through the elements in the constant struct or array and recursively 726 // look for virtual function pointers. 727 const DataLayout &DL = M.getDataLayout(); 728 if (auto *C = dyn_cast<ConstantStruct>(I)) { 729 StructType *STy = dyn_cast<StructType>(C->getType()); 730 assert(STy); 731 const StructLayout *SL = DL.getStructLayout(C->getType()); 732 733 for (auto EI : llvm::enumerate(STy->elements())) { 734 auto Offset = SL->getElementOffset(EI.index()); 735 unsigned Op = SL->getElementContainingOffset(Offset); 736 findFuncPointers(cast<Constant>(I->getOperand(Op)), 737 StartingOffset + Offset, M, Index, VTableFuncs, OrigGV); 738 } 739 } else if (auto *C = dyn_cast<ConstantArray>(I)) { 740 ArrayType *ATy = C->getType(); 741 Type *EltTy = ATy->getElementType(); 742 uint64_t EltSize = DL.getTypeAllocSize(EltTy); 743 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) { 744 findFuncPointers(cast<Constant>(I->getOperand(i)), 745 StartingOffset + i * EltSize, M, Index, VTableFuncs, 746 OrigGV); 747 } 748 } else if (const auto *CE = dyn_cast<ConstantExpr>(I)) { 749 // For relative vtables, the next sub-component should be a trunc. 750 if (CE->getOpcode() != Instruction::Trunc || 751 !(CE = dyn_cast<ConstantExpr>(CE->getOperand(0)))) 752 return; 753 754 // If this constant can be reduced to the offset between a function and a 755 // global, then we know this is a valid virtual function if the RHS is the 756 // original vtable we're scanning through. 757 if (CE->getOpcode() == Instruction::Sub) { 758 GlobalValue *LHS, *RHS; 759 APSInt LHSOffset, RHSOffset; 760 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHS, LHSOffset, DL) && 761 IsConstantOffsetFromGlobal(CE->getOperand(1), RHS, RHSOffset, DL) && 762 RHS == &OrigGV && 763 764 // For relative vtables, this component should point to the callable 765 // function without any offsets. 766 LHSOffset == 0 && 767 768 // Also, the RHS should always point to somewhere within the vtable. 769 RHSOffset <= 770 static_cast<uint64_t>(DL.getTypeAllocSize(OrigGV.getInitializer()->getType()))) { 771 findFuncPointers(LHS, StartingOffset, M, Index, VTableFuncs, OrigGV); 772 } 773 } 774 } 775 } 776 777 // Identify the function pointers referenced by vtable definition \p V. 778 static void computeVTableFuncs(ModuleSummaryIndex &Index, 779 const GlobalVariable &V, const Module &M, 780 VTableFuncList &VTableFuncs) { 781 if (!V.isConstant()) 782 return; 783 784 findFuncPointers(V.getInitializer(), /*StartingOffset=*/0, M, Index, 785 VTableFuncs, V); 786 787 #ifndef NDEBUG 788 // Validate that the VTableFuncs list is ordered by offset. 789 uint64_t PrevOffset = 0; 790 for (auto &P : VTableFuncs) { 791 // The findVFuncPointers traversal should have encountered the 792 // functions in offset order. We need to use ">=" since PrevOffset 793 // starts at 0. 794 assert(P.VTableOffset >= PrevOffset); 795 PrevOffset = P.VTableOffset; 796 } 797 #endif 798 } 799 800 /// Record vtable definition \p V for each type metadata it references. 801 static void 802 recordTypeIdCompatibleVtableReferences(ModuleSummaryIndex &Index, 803 const GlobalVariable &V, 804 SmallVectorImpl<MDNode *> &Types) { 805 for (MDNode *Type : Types) { 806 auto TypeID = Type->getOperand(1).get(); 807 808 uint64_t Offset = 809 cast<ConstantInt>( 810 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) 811 ->getZExtValue(); 812 813 if (auto *TypeId = dyn_cast<MDString>(TypeID)) 814 Index.getOrInsertTypeIdCompatibleVtableSummary(TypeId->getString()) 815 .push_back({Offset, Index.getOrInsertValueInfo(&V)}); 816 } 817 } 818 819 static void computeVariableSummary(ModuleSummaryIndex &Index, 820 const GlobalVariable &V, 821 DenseSet<GlobalValue::GUID> &CantBePromoted, 822 const Module &M, 823 SmallVectorImpl<MDNode *> &Types) { 824 SetVector<ValueInfo, SmallVector<ValueInfo, 0>> RefEdges; 825 SmallPtrSet<const User *, 8> Visited; 826 bool RefLocalIFunc = false; 827 bool HasBlockAddress = 828 findRefEdges(Index, &V, RefEdges, Visited, RefLocalIFunc); 829 const bool NotEligibleForImport = (HasBlockAddress || RefLocalIFunc); 830 bool NonRenamableLocal = isNonRenamableLocal(V); 831 GlobalValueSummary::GVFlags Flags( 832 V.getLinkage(), V.getVisibility(), NonRenamableLocal, 833 /* Live = */ false, V.isDSOLocal(), V.canBeOmittedFromSymbolTable(), 834 GlobalValueSummary::Definition); 835 836 VTableFuncList VTableFuncs; 837 // If splitting is not enabled, then we compute the summary information 838 // necessary for index-based whole program devirtualization. 839 if (!Index.enableSplitLTOUnit()) { 840 Types.clear(); 841 V.getMetadata(LLVMContext::MD_type, Types); 842 if (!Types.empty()) { 843 // Identify the function pointers referenced by this vtable definition. 844 computeVTableFuncs(Index, V, M, VTableFuncs); 845 846 // Record this vtable definition for each type metadata it references. 847 recordTypeIdCompatibleVtableReferences(Index, V, Types); 848 } 849 } 850 851 // Don't mark variables we won't be able to internalize as read/write-only. 852 bool CanBeInternalized = 853 !V.hasComdat() && !V.hasAppendingLinkage() && !V.isInterposable() && 854 !V.hasAvailableExternallyLinkage() && !V.hasDLLExportStorageClass(); 855 bool Constant = V.isConstant(); 856 GlobalVarSummary::GVarFlags VarFlags(CanBeInternalized, 857 Constant ? false : CanBeInternalized, 858 Constant, V.getVCallVisibility()); 859 auto GVarSummary = std::make_unique<GlobalVarSummary>(Flags, VarFlags, 860 RefEdges.takeVector()); 861 if (NonRenamableLocal) 862 CantBePromoted.insert(V.getGUID()); 863 if (NotEligibleForImport) 864 GVarSummary->setNotEligibleToImport(); 865 if (!VTableFuncs.empty()) 866 GVarSummary->setVTableFuncs(VTableFuncs); 867 Index.addGlobalValueSummary(V, std::move(GVarSummary)); 868 } 869 870 static void computeAliasSummary(ModuleSummaryIndex &Index, const GlobalAlias &A, 871 DenseSet<GlobalValue::GUID> &CantBePromoted) { 872 // Skip summary for indirect function aliases as summary for aliasee will not 873 // be emitted. 874 const GlobalObject *Aliasee = A.getAliaseeObject(); 875 if (isa<GlobalIFunc>(Aliasee)) 876 return; 877 bool NonRenamableLocal = isNonRenamableLocal(A); 878 GlobalValueSummary::GVFlags Flags( 879 A.getLinkage(), A.getVisibility(), NonRenamableLocal, 880 /* Live = */ false, A.isDSOLocal(), A.canBeOmittedFromSymbolTable(), 881 GlobalValueSummary::Definition); 882 auto AS = std::make_unique<AliasSummary>(Flags); 883 auto AliaseeVI = Index.getValueInfo(Aliasee->getGUID()); 884 assert(AliaseeVI && "Alias expects aliasee summary to be available"); 885 assert(AliaseeVI.getSummaryList().size() == 1 && 886 "Expected a single entry per aliasee in per-module index"); 887 AS->setAliasee(AliaseeVI, AliaseeVI.getSummaryList()[0].get()); 888 if (NonRenamableLocal) 889 CantBePromoted.insert(A.getGUID()); 890 Index.addGlobalValueSummary(A, std::move(AS)); 891 } 892 893 // Set LiveRoot flag on entries matching the given value name. 894 static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) { 895 if (ValueInfo VI = Index.getValueInfo(GlobalValue::getGUID(Name))) 896 for (const auto &Summary : VI.getSummaryList()) 897 Summary->setLive(true); 898 } 899 900 ModuleSummaryIndex llvm::buildModuleSummaryIndex( 901 const Module &M, 902 std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback, 903 ProfileSummaryInfo *PSI, 904 std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback) { 905 assert(PSI); 906 bool EnableSplitLTOUnit = false; 907 bool UnifiedLTO = false; 908 if (auto *MD = mdconst::extract_or_null<ConstantInt>( 909 M.getModuleFlag("EnableSplitLTOUnit"))) 910 EnableSplitLTOUnit = MD->getZExtValue(); 911 if (auto *MD = 912 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("UnifiedLTO"))) 913 UnifiedLTO = MD->getZExtValue(); 914 ModuleSummaryIndex Index(/*HaveGVs=*/true, EnableSplitLTOUnit, UnifiedLTO); 915 916 // Identify the local values in the llvm.used and llvm.compiler.used sets, 917 // which should not be exported as they would then require renaming and 918 // promotion, but we may have opaque uses e.g. in inline asm. We collect them 919 // here because we use this information to mark functions containing inline 920 // assembly calls as not importable. 921 SmallPtrSet<GlobalValue *, 4> LocalsUsed; 922 SmallVector<GlobalValue *, 4> Used; 923 // First collect those in the llvm.used set. 924 collectUsedGlobalVariables(M, Used, /*CompilerUsed=*/false); 925 // Next collect those in the llvm.compiler.used set. 926 collectUsedGlobalVariables(M, Used, /*CompilerUsed=*/true); 927 DenseSet<GlobalValue::GUID> CantBePromoted; 928 for (auto *V : Used) { 929 if (V->hasLocalLinkage()) { 930 LocalsUsed.insert(V); 931 CantBePromoted.insert(V->getGUID()); 932 } 933 } 934 935 bool HasLocalInlineAsmSymbol = false; 936 if (!M.getModuleInlineAsm().empty()) { 937 // Collect the local values defined by module level asm, and set up 938 // summaries for these symbols so that they can be marked as NoRename, 939 // to prevent export of any use of them in regular IR that would require 940 // renaming within the module level asm. Note we don't need to create a 941 // summary for weak or global defs, as they don't need to be flagged as 942 // NoRename, and defs in module level asm can't be imported anyway. 943 // Also, any values used but not defined within module level asm should 944 // be listed on the llvm.used or llvm.compiler.used global and marked as 945 // referenced from there. 946 ModuleSymbolTable::CollectAsmSymbols( 947 M, [&](StringRef Name, object::BasicSymbolRef::Flags Flags) { 948 // Symbols not marked as Weak or Global are local definitions. 949 if (Flags & (object::BasicSymbolRef::SF_Weak | 950 object::BasicSymbolRef::SF_Global)) 951 return; 952 HasLocalInlineAsmSymbol = true; 953 GlobalValue *GV = M.getNamedValue(Name); 954 if (!GV) 955 return; 956 assert(GV->isDeclaration() && "Def in module asm already has definition"); 957 GlobalValueSummary::GVFlags GVFlags( 958 GlobalValue::InternalLinkage, GlobalValue::DefaultVisibility, 959 /* NotEligibleToImport = */ true, 960 /* Live = */ true, 961 /* Local */ GV->isDSOLocal(), GV->canBeOmittedFromSymbolTable(), 962 GlobalValueSummary::Definition); 963 CantBePromoted.insert(GV->getGUID()); 964 // Create the appropriate summary type. 965 if (Function *F = dyn_cast<Function>(GV)) { 966 std::unique_ptr<FunctionSummary> Summary = 967 std::make_unique<FunctionSummary>( 968 GVFlags, /*InstCount=*/0, 969 FunctionSummary::FFlags{ 970 F->hasFnAttribute(Attribute::ReadNone), 971 F->hasFnAttribute(Attribute::ReadOnly), 972 F->hasFnAttribute(Attribute::NoRecurse), 973 F->returnDoesNotAlias(), 974 /* NoInline = */ false, 975 F->hasFnAttribute(Attribute::AlwaysInline), 976 F->hasFnAttribute(Attribute::NoUnwind), 977 /* MayThrow */ true, 978 /* HasUnknownCall */ true, 979 /* MustBeUnreachable */ false}, 980 SmallVector<ValueInfo, 0>{}, 981 SmallVector<FunctionSummary::EdgeTy, 0>{}, 982 ArrayRef<GlobalValue::GUID>{}, 983 ArrayRef<FunctionSummary::VFuncId>{}, 984 ArrayRef<FunctionSummary::VFuncId>{}, 985 ArrayRef<FunctionSummary::ConstVCall>{}, 986 ArrayRef<FunctionSummary::ConstVCall>{}, 987 ArrayRef<FunctionSummary::ParamAccess>{}, 988 ArrayRef<CallsiteInfo>{}, ArrayRef<AllocInfo>{}); 989 Index.addGlobalValueSummary(*GV, std::move(Summary)); 990 } else { 991 std::unique_ptr<GlobalVarSummary> Summary = 992 std::make_unique<GlobalVarSummary>( 993 GVFlags, 994 GlobalVarSummary::GVarFlags( 995 false, false, cast<GlobalVariable>(GV)->isConstant(), 996 GlobalObject::VCallVisibilityPublic), 997 SmallVector<ValueInfo, 0>{}); 998 Index.addGlobalValueSummary(*GV, std::move(Summary)); 999 } 1000 }); 1001 } 1002 1003 bool IsThinLTO = true; 1004 if (auto *MD = 1005 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO"))) 1006 IsThinLTO = MD->getZExtValue(); 1007 1008 // Compute summaries for all functions defined in module, and save in the 1009 // index. 1010 for (const auto &F : M) { 1011 if (F.isDeclaration()) 1012 continue; 1013 1014 DominatorTree DT(const_cast<Function &>(F)); 1015 BlockFrequencyInfo *BFI = nullptr; 1016 std::unique_ptr<BlockFrequencyInfo> BFIPtr; 1017 if (GetBFICallback) 1018 BFI = GetBFICallback(F); 1019 else if (F.hasProfileData()) { 1020 LoopInfo LI{DT}; 1021 BranchProbabilityInfo BPI{F, LI}; 1022 BFIPtr = std::make_unique<BlockFrequencyInfo>(F, BPI, LI); 1023 BFI = BFIPtr.get(); 1024 } 1025 1026 computeFunctionSummary(Index, M, F, BFI, PSI, DT, 1027 !LocalsUsed.empty() || HasLocalInlineAsmSymbol, 1028 CantBePromoted, IsThinLTO, GetSSICallback); 1029 } 1030 1031 // Compute summaries for all variables defined in module, and save in the 1032 // index. 1033 SmallVector<MDNode *, 2> Types; 1034 for (const GlobalVariable &G : M.globals()) { 1035 if (G.isDeclaration()) 1036 continue; 1037 computeVariableSummary(Index, G, CantBePromoted, M, Types); 1038 } 1039 1040 // Compute summaries for all aliases defined in module, and save in the 1041 // index. 1042 for (const GlobalAlias &A : M.aliases()) 1043 computeAliasSummary(Index, A, CantBePromoted); 1044 1045 // Iterate through ifuncs, set their resolvers all alive. 1046 for (const GlobalIFunc &I : M.ifuncs()) { 1047 I.applyAlongResolverPath([&Index](const GlobalValue &GV) { 1048 Index.getGlobalValueSummary(GV)->setLive(true); 1049 }); 1050 } 1051 1052 for (auto *V : LocalsUsed) { 1053 auto *Summary = Index.getGlobalValueSummary(*V); 1054 assert(Summary && "Missing summary for global value"); 1055 Summary->setNotEligibleToImport(); 1056 } 1057 1058 // The linker doesn't know about these LLVM produced values, so we need 1059 // to flag them as live in the index to ensure index-based dead value 1060 // analysis treats them as live roots of the analysis. 1061 setLiveRoot(Index, "llvm.used"); 1062 setLiveRoot(Index, "llvm.compiler.used"); 1063 setLiveRoot(Index, "llvm.global_ctors"); 1064 setLiveRoot(Index, "llvm.global_dtors"); 1065 setLiveRoot(Index, "llvm.global.annotations"); 1066 1067 for (auto &GlobalList : Index) { 1068 // Ignore entries for references that are undefined in the current module. 1069 if (GlobalList.second.SummaryList.empty()) 1070 continue; 1071 1072 assert(GlobalList.second.SummaryList.size() == 1 && 1073 "Expected module's index to have one summary per GUID"); 1074 auto &Summary = GlobalList.second.SummaryList[0]; 1075 if (!IsThinLTO) { 1076 Summary->setNotEligibleToImport(); 1077 continue; 1078 } 1079 1080 bool AllRefsCanBeExternallyReferenced = 1081 llvm::all_of(Summary->refs(), [&](const ValueInfo &VI) { 1082 return !CantBePromoted.count(VI.getGUID()); 1083 }); 1084 if (!AllRefsCanBeExternallyReferenced) { 1085 Summary->setNotEligibleToImport(); 1086 continue; 1087 } 1088 1089 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) { 1090 bool AllCallsCanBeExternallyReferenced = llvm::all_of( 1091 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) { 1092 return !CantBePromoted.count(Edge.first.getGUID()); 1093 }); 1094 if (!AllCallsCanBeExternallyReferenced) 1095 Summary->setNotEligibleToImport(); 1096 } 1097 } 1098 1099 if (!ModuleSummaryDotFile.empty()) { 1100 std::error_code EC; 1101 raw_fd_ostream OSDot(ModuleSummaryDotFile, EC, sys::fs::OpenFlags::OF_Text); 1102 if (EC) 1103 report_fatal_error(Twine("Failed to open dot file ") + 1104 ModuleSummaryDotFile + ": " + EC.message() + "\n"); 1105 Index.exportToDot(OSDot, {}); 1106 } 1107 1108 return Index; 1109 } 1110 1111 AnalysisKey ModuleSummaryIndexAnalysis::Key; 1112 1113 ModuleSummaryIndex 1114 ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) { 1115 ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M); 1116 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1117 bool NeedSSI = needsParamAccessSummary(M); 1118 return buildModuleSummaryIndex( 1119 M, 1120 [&FAM](const Function &F) { 1121 return &FAM.getResult<BlockFrequencyAnalysis>( 1122 *const_cast<Function *>(&F)); 1123 }, 1124 &PSI, 1125 [&FAM, NeedSSI](const Function &F) -> const StackSafetyInfo * { 1126 return NeedSSI ? &FAM.getResult<StackSafetyAnalysis>( 1127 const_cast<Function &>(F)) 1128 : nullptr; 1129 }); 1130 } 1131 1132 char ModuleSummaryIndexWrapperPass::ID = 0; 1133 1134 INITIALIZE_PASS_BEGIN(ModuleSummaryIndexWrapperPass, "module-summary-analysis", 1135 "Module Summary Analysis", false, true) 1136 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 1137 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 1138 INITIALIZE_PASS_DEPENDENCY(StackSafetyInfoWrapperPass) 1139 INITIALIZE_PASS_END(ModuleSummaryIndexWrapperPass, "module-summary-analysis", 1140 "Module Summary Analysis", false, true) 1141 1142 ModulePass *llvm::createModuleSummaryIndexWrapperPass() { 1143 return new ModuleSummaryIndexWrapperPass(); 1144 } 1145 1146 ModuleSummaryIndexWrapperPass::ModuleSummaryIndexWrapperPass() 1147 : ModulePass(ID) { 1148 initializeModuleSummaryIndexWrapperPassPass(*PassRegistry::getPassRegistry()); 1149 } 1150 1151 bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) { 1152 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 1153 bool NeedSSI = needsParamAccessSummary(M); 1154 Index.emplace(buildModuleSummaryIndex( 1155 M, 1156 [this](const Function &F) { 1157 return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>( 1158 *const_cast<Function *>(&F)) 1159 .getBFI()); 1160 }, 1161 PSI, 1162 [&](const Function &F) -> const StackSafetyInfo * { 1163 return NeedSSI ? &getAnalysis<StackSafetyInfoWrapperPass>( 1164 const_cast<Function &>(F)) 1165 .getResult() 1166 : nullptr; 1167 })); 1168 return false; 1169 } 1170 1171 bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) { 1172 Index.reset(); 1173 return false; 1174 } 1175 1176 void ModuleSummaryIndexWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1177 AU.setPreservesAll(); 1178 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 1179 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 1180 AU.addRequired<StackSafetyInfoWrapperPass>(); 1181 } 1182 1183 char ImmutableModuleSummaryIndexWrapperPass::ID = 0; 1184 1185 ImmutableModuleSummaryIndexWrapperPass::ImmutableModuleSummaryIndexWrapperPass( 1186 const ModuleSummaryIndex *Index) 1187 : ImmutablePass(ID), Index(Index) { 1188 initializeImmutableModuleSummaryIndexWrapperPassPass( 1189 *PassRegistry::getPassRegistry()); 1190 } 1191 1192 void ImmutableModuleSummaryIndexWrapperPass::getAnalysisUsage( 1193 AnalysisUsage &AU) const { 1194 AU.setPreservesAll(); 1195 } 1196 1197 ImmutablePass *llvm::createImmutableModuleSummaryIndexWrapperPass( 1198 const ModuleSummaryIndex *Index) { 1199 return new ImmutableModuleSummaryIndexWrapperPass(Index); 1200 } 1201 1202 INITIALIZE_PASS(ImmutableModuleSummaryIndexWrapperPass, "module-summary-info", 1203 "Module summary info", false, true) 1204 1205 bool llvm::mayHaveMemprofSummary(const CallBase *CB) { 1206 if (!CB) 1207 return false; 1208 if (CB->isDebugOrPseudoInst()) 1209 return false; 1210 auto *CI = dyn_cast<CallInst>(CB); 1211 auto *CalledValue = CB->getCalledOperand(); 1212 auto *CalledFunction = CB->getCalledFunction(); 1213 if (CalledValue && !CalledFunction) { 1214 CalledValue = CalledValue->stripPointerCasts(); 1215 // Stripping pointer casts can reveal a called function. 1216 CalledFunction = dyn_cast<Function>(CalledValue); 1217 } 1218 // Check if this is an alias to a function. If so, get the 1219 // called aliasee for the checks below. 1220 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) { 1221 assert(!CalledFunction && 1222 "Expected null called function in callsite for alias"); 1223 CalledFunction = dyn_cast<Function>(GA->getAliaseeObject()); 1224 } 1225 // Check if this is a direct call to a known function or a known 1226 // intrinsic, or an indirect call with profile data. 1227 if (CalledFunction) { 1228 if (CI && CalledFunction->isIntrinsic()) 1229 return false; 1230 } else { 1231 // Skip indirect calls if we haven't enabled memprof ICP. 1232 if (!EnableMemProfIndirectCallSupport) 1233 return false; 1234 // Skip inline assembly calls. 1235 if (CI && CI->isInlineAsm()) 1236 return false; 1237 // Skip direct calls via Constant. 1238 if (!CalledValue || isa<Constant>(CalledValue)) 1239 return false; 1240 return true; 1241 } 1242 return true; 1243 } 1244