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