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