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