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