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