17330f729Sjoerg //===- ModuleSummaryAnalysis.cpp - Module summary index builder -----------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This pass builds a ModuleSummaryIndex object for the module, to be written
107330f729Sjoerg // to bitcode or LLVM assembly.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg
147330f729Sjoerg #include "llvm/Analysis/ModuleSummaryAnalysis.h"
157330f729Sjoerg #include "llvm/ADT/ArrayRef.h"
167330f729Sjoerg #include "llvm/ADT/DenseSet.h"
177330f729Sjoerg #include "llvm/ADT/MapVector.h"
187330f729Sjoerg #include "llvm/ADT/STLExtras.h"
197330f729Sjoerg #include "llvm/ADT/SetVector.h"
207330f729Sjoerg #include "llvm/ADT/SmallPtrSet.h"
217330f729Sjoerg #include "llvm/ADT/SmallVector.h"
227330f729Sjoerg #include "llvm/ADT/StringRef.h"
237330f729Sjoerg #include "llvm/Analysis/BlockFrequencyInfo.h"
247330f729Sjoerg #include "llvm/Analysis/BranchProbabilityInfo.h"
257330f729Sjoerg #include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
267330f729Sjoerg #include "llvm/Analysis/LoopInfo.h"
277330f729Sjoerg #include "llvm/Analysis/ProfileSummaryInfo.h"
28*82d56013Sjoerg #include "llvm/Analysis/StackSafetyAnalysis.h"
297330f729Sjoerg #include "llvm/Analysis/TypeMetadataUtils.h"
307330f729Sjoerg #include "llvm/IR/Attributes.h"
317330f729Sjoerg #include "llvm/IR/BasicBlock.h"
327330f729Sjoerg #include "llvm/IR/Constant.h"
337330f729Sjoerg #include "llvm/IR/Constants.h"
347330f729Sjoerg #include "llvm/IR/Dominators.h"
357330f729Sjoerg #include "llvm/IR/Function.h"
367330f729Sjoerg #include "llvm/IR/GlobalAlias.h"
377330f729Sjoerg #include "llvm/IR/GlobalValue.h"
387330f729Sjoerg #include "llvm/IR/GlobalVariable.h"
397330f729Sjoerg #include "llvm/IR/Instructions.h"
407330f729Sjoerg #include "llvm/IR/IntrinsicInst.h"
417330f729Sjoerg #include "llvm/IR/Intrinsics.h"
427330f729Sjoerg #include "llvm/IR/Metadata.h"
437330f729Sjoerg #include "llvm/IR/Module.h"
447330f729Sjoerg #include "llvm/IR/ModuleSummaryIndex.h"
457330f729Sjoerg #include "llvm/IR/Use.h"
467330f729Sjoerg #include "llvm/IR/User.h"
47*82d56013Sjoerg #include "llvm/InitializePasses.h"
487330f729Sjoerg #include "llvm/Object/ModuleSymbolTable.h"
497330f729Sjoerg #include "llvm/Object/SymbolicFile.h"
507330f729Sjoerg #include "llvm/Pass.h"
517330f729Sjoerg #include "llvm/Support/Casting.h"
527330f729Sjoerg #include "llvm/Support/CommandLine.h"
53*82d56013Sjoerg #include "llvm/Support/FileSystem.h"
547330f729Sjoerg #include <algorithm>
557330f729Sjoerg #include <cassert>
567330f729Sjoerg #include <cstdint>
577330f729Sjoerg #include <vector>
587330f729Sjoerg
597330f729Sjoerg using namespace llvm;
607330f729Sjoerg
617330f729Sjoerg #define DEBUG_TYPE "module-summary-analysis"
627330f729Sjoerg
637330f729Sjoerg // Option to force edges cold which will block importing when the
647330f729Sjoerg // -import-cold-multiplier is set to 0. Useful for debugging.
657330f729Sjoerg FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold =
667330f729Sjoerg FunctionSummary::FSHT_None;
677330f729Sjoerg cl::opt<FunctionSummary::ForceSummaryHotnessType, true> FSEC(
687330f729Sjoerg "force-summary-edges-cold", cl::Hidden, cl::location(ForceSummaryEdgesCold),
697330f729Sjoerg cl::desc("Force all edges in the function summary to cold"),
707330f729Sjoerg cl::values(clEnumValN(FunctionSummary::FSHT_None, "none", "None."),
717330f729Sjoerg clEnumValN(FunctionSummary::FSHT_AllNonCritical,
727330f729Sjoerg "all-non-critical", "All non-critical edges."),
737330f729Sjoerg clEnumValN(FunctionSummary::FSHT_All, "all", "All edges.")));
747330f729Sjoerg
757330f729Sjoerg cl::opt<std::string> ModuleSummaryDotFile(
767330f729Sjoerg "module-summary-dot-file", cl::init(""), cl::Hidden,
777330f729Sjoerg cl::value_desc("filename"),
787330f729Sjoerg cl::desc("File to emit dot graph of new summary into."));
797330f729Sjoerg
807330f729Sjoerg // Walk through the operands of a given User via worklist iteration and populate
817330f729Sjoerg // the set of GlobalValue references encountered. Invoked either on an
827330f729Sjoerg // Instruction or a GlobalVariable (which walks its initializer).
837330f729Sjoerg // Return true if any of the operands contains blockaddress. This is important
847330f729Sjoerg // to know when computing summary for global var, because if global variable
857330f729Sjoerg // references basic block address we can't import it separately from function
867330f729Sjoerg // containing that basic block. For simplicity we currently don't import such
877330f729Sjoerg // global vars at all. When importing function we aren't interested if any
887330f729Sjoerg // instruction in it takes an address of any basic block, because instruction
897330f729Sjoerg // can only take an address of basic block located in the same function.
findRefEdges(ModuleSummaryIndex & Index,const User * CurUser,SetVector<ValueInfo> & RefEdges,SmallPtrSet<const User *,8> & Visited)907330f729Sjoerg static bool findRefEdges(ModuleSummaryIndex &Index, const User *CurUser,
917330f729Sjoerg SetVector<ValueInfo> &RefEdges,
927330f729Sjoerg SmallPtrSet<const User *, 8> &Visited) {
937330f729Sjoerg bool HasBlockAddress = false;
947330f729Sjoerg SmallVector<const User *, 32> Worklist;
95*82d56013Sjoerg if (Visited.insert(CurUser).second)
967330f729Sjoerg Worklist.push_back(CurUser);
977330f729Sjoerg
987330f729Sjoerg while (!Worklist.empty()) {
997330f729Sjoerg const User *U = Worklist.pop_back_val();
100*82d56013Sjoerg const auto *CB = dyn_cast<CallBase>(U);
1017330f729Sjoerg
1027330f729Sjoerg for (const auto &OI : U->operands()) {
1037330f729Sjoerg const User *Operand = dyn_cast<User>(OI);
1047330f729Sjoerg if (!Operand)
1057330f729Sjoerg continue;
1067330f729Sjoerg if (isa<BlockAddress>(Operand)) {
1077330f729Sjoerg HasBlockAddress = true;
1087330f729Sjoerg continue;
1097330f729Sjoerg }
1107330f729Sjoerg if (auto *GV = dyn_cast<GlobalValue>(Operand)) {
1117330f729Sjoerg // We have a reference to a global value. This should be added to
1127330f729Sjoerg // the reference set unless it is a callee. Callees are handled
1137330f729Sjoerg // specially by WriteFunction and are added to a separate list.
114*82d56013Sjoerg if (!(CB && CB->isCallee(&OI)))
1157330f729Sjoerg RefEdges.insert(Index.getOrInsertValueInfo(GV));
1167330f729Sjoerg continue;
1177330f729Sjoerg }
118*82d56013Sjoerg if (Visited.insert(Operand).second)
1197330f729Sjoerg Worklist.push_back(Operand);
1207330f729Sjoerg }
1217330f729Sjoerg }
1227330f729Sjoerg return HasBlockAddress;
1237330f729Sjoerg }
1247330f729Sjoerg
getHotness(uint64_t ProfileCount,ProfileSummaryInfo * PSI)1257330f729Sjoerg static CalleeInfo::HotnessType getHotness(uint64_t ProfileCount,
1267330f729Sjoerg ProfileSummaryInfo *PSI) {
1277330f729Sjoerg if (!PSI)
1287330f729Sjoerg return CalleeInfo::HotnessType::Unknown;
1297330f729Sjoerg if (PSI->isHotCount(ProfileCount))
1307330f729Sjoerg return CalleeInfo::HotnessType::Hot;
1317330f729Sjoerg if (PSI->isColdCount(ProfileCount))
1327330f729Sjoerg return CalleeInfo::HotnessType::Cold;
1337330f729Sjoerg return CalleeInfo::HotnessType::None;
1347330f729Sjoerg }
1357330f729Sjoerg
isNonRenamableLocal(const GlobalValue & GV)1367330f729Sjoerg static bool isNonRenamableLocal(const GlobalValue &GV) {
1377330f729Sjoerg return GV.hasSection() && GV.hasLocalLinkage();
1387330f729Sjoerg }
1397330f729Sjoerg
1407330f729Sjoerg /// Determine whether this call has all constant integer arguments (excluding
1417330f729Sjoerg /// "this") and summarize it to VCalls or ConstVCalls as appropriate.
addVCallToSet(DevirtCallSite Call,GlobalValue::GUID Guid,SetVector<FunctionSummary::VFuncId> & VCalls,SetVector<FunctionSummary::ConstVCall> & ConstVCalls)1427330f729Sjoerg static void addVCallToSet(DevirtCallSite Call, GlobalValue::GUID Guid,
1437330f729Sjoerg SetVector<FunctionSummary::VFuncId> &VCalls,
1447330f729Sjoerg SetVector<FunctionSummary::ConstVCall> &ConstVCalls) {
1457330f729Sjoerg std::vector<uint64_t> Args;
1467330f729Sjoerg // Start from the second argument to skip the "this" pointer.
147*82d56013Sjoerg for (auto &Arg : drop_begin(Call.CB.args())) {
1487330f729Sjoerg auto *CI = dyn_cast<ConstantInt>(Arg);
1497330f729Sjoerg if (!CI || CI->getBitWidth() > 64) {
1507330f729Sjoerg VCalls.insert({Guid, Call.Offset});
1517330f729Sjoerg return;
1527330f729Sjoerg }
1537330f729Sjoerg Args.push_back(CI->getZExtValue());
1547330f729Sjoerg }
1557330f729Sjoerg ConstVCalls.insert({{Guid, Call.Offset}, std::move(Args)});
1567330f729Sjoerg }
1577330f729Sjoerg
1587330f729Sjoerg /// If this intrinsic call requires that we add information to the function
1597330f729Sjoerg /// summary, do so via the non-constant reference arguments.
addIntrinsicToSummary(const CallInst * CI,SetVector<GlobalValue::GUID> & TypeTests,SetVector<FunctionSummary::VFuncId> & TypeTestAssumeVCalls,SetVector<FunctionSummary::VFuncId> & TypeCheckedLoadVCalls,SetVector<FunctionSummary::ConstVCall> & TypeTestAssumeConstVCalls,SetVector<FunctionSummary::ConstVCall> & TypeCheckedLoadConstVCalls,DominatorTree & DT)1607330f729Sjoerg static void addIntrinsicToSummary(
1617330f729Sjoerg const CallInst *CI, SetVector<GlobalValue::GUID> &TypeTests,
1627330f729Sjoerg SetVector<FunctionSummary::VFuncId> &TypeTestAssumeVCalls,
1637330f729Sjoerg SetVector<FunctionSummary::VFuncId> &TypeCheckedLoadVCalls,
1647330f729Sjoerg SetVector<FunctionSummary::ConstVCall> &TypeTestAssumeConstVCalls,
1657330f729Sjoerg SetVector<FunctionSummary::ConstVCall> &TypeCheckedLoadConstVCalls,
1667330f729Sjoerg DominatorTree &DT) {
1677330f729Sjoerg switch (CI->getCalledFunction()->getIntrinsicID()) {
1687330f729Sjoerg case Intrinsic::type_test: {
1697330f729Sjoerg auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1));
1707330f729Sjoerg auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
1717330f729Sjoerg if (!TypeId)
1727330f729Sjoerg break;
1737330f729Sjoerg GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
1747330f729Sjoerg
1757330f729Sjoerg // Produce a summary from type.test intrinsics. We only summarize type.test
1767330f729Sjoerg // intrinsics that are used other than by an llvm.assume intrinsic.
1777330f729Sjoerg // Intrinsics that are assumed are relevant only to the devirtualization
1787330f729Sjoerg // pass, not the type test lowering pass.
1797330f729Sjoerg bool HasNonAssumeUses = llvm::any_of(CI->uses(), [](const Use &CIU) {
180*82d56013Sjoerg return !isa<AssumeInst>(CIU.getUser());
1817330f729Sjoerg });
1827330f729Sjoerg if (HasNonAssumeUses)
1837330f729Sjoerg TypeTests.insert(Guid);
1847330f729Sjoerg
1857330f729Sjoerg SmallVector<DevirtCallSite, 4> DevirtCalls;
1867330f729Sjoerg SmallVector<CallInst *, 4> Assumes;
1877330f729Sjoerg findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
1887330f729Sjoerg for (auto &Call : DevirtCalls)
1897330f729Sjoerg addVCallToSet(Call, Guid, TypeTestAssumeVCalls,
1907330f729Sjoerg TypeTestAssumeConstVCalls);
1917330f729Sjoerg
1927330f729Sjoerg break;
1937330f729Sjoerg }
1947330f729Sjoerg
1957330f729Sjoerg case Intrinsic::type_checked_load: {
1967330f729Sjoerg auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(2));
1977330f729Sjoerg auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
1987330f729Sjoerg if (!TypeId)
1997330f729Sjoerg break;
2007330f729Sjoerg GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
2017330f729Sjoerg
2027330f729Sjoerg SmallVector<DevirtCallSite, 4> DevirtCalls;
2037330f729Sjoerg SmallVector<Instruction *, 4> LoadedPtrs;
2047330f729Sjoerg SmallVector<Instruction *, 4> Preds;
2057330f729Sjoerg bool HasNonCallUses = false;
2067330f729Sjoerg findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
2077330f729Sjoerg HasNonCallUses, CI, DT);
2087330f729Sjoerg // Any non-call uses of the result of llvm.type.checked.load will
2097330f729Sjoerg // prevent us from optimizing away the llvm.type.test.
2107330f729Sjoerg if (HasNonCallUses)
2117330f729Sjoerg TypeTests.insert(Guid);
2127330f729Sjoerg for (auto &Call : DevirtCalls)
2137330f729Sjoerg addVCallToSet(Call, Guid, TypeCheckedLoadVCalls,
2147330f729Sjoerg TypeCheckedLoadConstVCalls);
2157330f729Sjoerg
2167330f729Sjoerg break;
2177330f729Sjoerg }
2187330f729Sjoerg default:
2197330f729Sjoerg break;
2207330f729Sjoerg }
2217330f729Sjoerg }
2227330f729Sjoerg
isNonVolatileLoad(const Instruction * I)2237330f729Sjoerg static bool isNonVolatileLoad(const Instruction *I) {
2247330f729Sjoerg if (const auto *LI = dyn_cast<LoadInst>(I))
2257330f729Sjoerg return !LI->isVolatile();
2267330f729Sjoerg
2277330f729Sjoerg return false;
2287330f729Sjoerg }
2297330f729Sjoerg
isNonVolatileStore(const Instruction * I)2307330f729Sjoerg static bool isNonVolatileStore(const Instruction *I) {
2317330f729Sjoerg if (const auto *SI = dyn_cast<StoreInst>(I))
2327330f729Sjoerg return !SI->isVolatile();
2337330f729Sjoerg
2347330f729Sjoerg return false;
2357330f729Sjoerg }
2367330f729Sjoerg
computeFunctionSummary(ModuleSummaryIndex & Index,const Module & M,const Function & F,BlockFrequencyInfo * BFI,ProfileSummaryInfo * PSI,DominatorTree & DT,bool HasLocalsInUsedOrAsm,DenseSet<GlobalValue::GUID> & CantBePromoted,bool IsThinLTO,std::function<const StackSafetyInfo * (const Function & F)> GetSSICallback)237*82d56013Sjoerg static void computeFunctionSummary(
238*82d56013Sjoerg ModuleSummaryIndex &Index, const Module &M, const Function &F,
239*82d56013Sjoerg BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, DominatorTree &DT,
240*82d56013Sjoerg bool HasLocalsInUsedOrAsm, DenseSet<GlobalValue::GUID> &CantBePromoted,
241*82d56013Sjoerg bool IsThinLTO,
242*82d56013Sjoerg std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback) {
2437330f729Sjoerg // Summary not currently supported for anonymous functions, they should
2447330f729Sjoerg // have been named.
2457330f729Sjoerg assert(F.hasName());
2467330f729Sjoerg
2477330f729Sjoerg unsigned NumInsts = 0;
2487330f729Sjoerg // Map from callee ValueId to profile count. Used to accumulate profile
2497330f729Sjoerg // counts for all static calls to a given callee.
2507330f729Sjoerg MapVector<ValueInfo, CalleeInfo> CallGraphEdges;
2517330f729Sjoerg SetVector<ValueInfo> RefEdges, LoadRefEdges, StoreRefEdges;
2527330f729Sjoerg SetVector<GlobalValue::GUID> TypeTests;
2537330f729Sjoerg SetVector<FunctionSummary::VFuncId> TypeTestAssumeVCalls,
2547330f729Sjoerg TypeCheckedLoadVCalls;
2557330f729Sjoerg SetVector<FunctionSummary::ConstVCall> TypeTestAssumeConstVCalls,
2567330f729Sjoerg TypeCheckedLoadConstVCalls;
2577330f729Sjoerg ICallPromotionAnalysis ICallAnalysis;
2587330f729Sjoerg SmallPtrSet<const User *, 8> Visited;
2597330f729Sjoerg
2607330f729Sjoerg // Add personality function, prefix data and prologue data to function's ref
2617330f729Sjoerg // list.
2627330f729Sjoerg findRefEdges(Index, &F, RefEdges, Visited);
2637330f729Sjoerg std::vector<const Instruction *> NonVolatileLoads;
2647330f729Sjoerg std::vector<const Instruction *> NonVolatileStores;
2657330f729Sjoerg
2667330f729Sjoerg bool HasInlineAsmMaybeReferencingInternal = false;
2677330f729Sjoerg for (const BasicBlock &BB : F)
2687330f729Sjoerg for (const Instruction &I : BB) {
2697330f729Sjoerg if (isa<DbgInfoIntrinsic>(I))
2707330f729Sjoerg continue;
2717330f729Sjoerg ++NumInsts;
2727330f729Sjoerg // Regular LTO module doesn't participate in ThinLTO import,
2737330f729Sjoerg // so no reference from it can be read/writeonly, since this
2747330f729Sjoerg // would require importing variable as local copy
2757330f729Sjoerg if (IsThinLTO) {
2767330f729Sjoerg if (isNonVolatileLoad(&I)) {
2777330f729Sjoerg // Postpone processing of non-volatile load instructions
2787330f729Sjoerg // See comments below
2797330f729Sjoerg Visited.insert(&I);
2807330f729Sjoerg NonVolatileLoads.push_back(&I);
2817330f729Sjoerg continue;
2827330f729Sjoerg } else if (isNonVolatileStore(&I)) {
2837330f729Sjoerg Visited.insert(&I);
2847330f729Sjoerg NonVolatileStores.push_back(&I);
2857330f729Sjoerg // All references from second operand of store (destination address)
2867330f729Sjoerg // can be considered write-only if they're not referenced by any
2877330f729Sjoerg // non-store instruction. References from first operand of store
2887330f729Sjoerg // (stored value) can't be treated either as read- or as write-only
2897330f729Sjoerg // so we add them to RefEdges as we do with all other instructions
2907330f729Sjoerg // except non-volatile load.
2917330f729Sjoerg Value *Stored = I.getOperand(0);
2927330f729Sjoerg if (auto *GV = dyn_cast<GlobalValue>(Stored))
2937330f729Sjoerg // findRefEdges will try to examine GV operands, so instead
2947330f729Sjoerg // of calling it we should add GV to RefEdges directly.
2957330f729Sjoerg RefEdges.insert(Index.getOrInsertValueInfo(GV));
2967330f729Sjoerg else if (auto *U = dyn_cast<User>(Stored))
2977330f729Sjoerg findRefEdges(Index, U, RefEdges, Visited);
2987330f729Sjoerg continue;
2997330f729Sjoerg }
3007330f729Sjoerg }
3017330f729Sjoerg findRefEdges(Index, &I, RefEdges, Visited);
302*82d56013Sjoerg const auto *CB = dyn_cast<CallBase>(&I);
303*82d56013Sjoerg if (!CB)
3047330f729Sjoerg continue;
3057330f729Sjoerg
3067330f729Sjoerg const auto *CI = dyn_cast<CallInst>(&I);
3077330f729Sjoerg // Since we don't know exactly which local values are referenced in inline
3087330f729Sjoerg // assembly, conservatively mark the function as possibly referencing
3097330f729Sjoerg // a local value from inline assembly to ensure we don't export a
3107330f729Sjoerg // reference (which would require renaming and promotion of the
3117330f729Sjoerg // referenced value).
3127330f729Sjoerg if (HasLocalsInUsedOrAsm && CI && CI->isInlineAsm())
3137330f729Sjoerg HasInlineAsmMaybeReferencingInternal = true;
3147330f729Sjoerg
315*82d56013Sjoerg auto *CalledValue = CB->getCalledOperand();
316*82d56013Sjoerg auto *CalledFunction = CB->getCalledFunction();
3177330f729Sjoerg if (CalledValue && !CalledFunction) {
3187330f729Sjoerg CalledValue = CalledValue->stripPointerCasts();
3197330f729Sjoerg // Stripping pointer casts can reveal a called function.
3207330f729Sjoerg CalledFunction = dyn_cast<Function>(CalledValue);
3217330f729Sjoerg }
3227330f729Sjoerg // Check if this is an alias to a function. If so, get the
3237330f729Sjoerg // called aliasee for the checks below.
3247330f729Sjoerg if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
3257330f729Sjoerg assert(!CalledFunction && "Expected null called function in callsite for alias");
3267330f729Sjoerg CalledFunction = dyn_cast<Function>(GA->getBaseObject());
3277330f729Sjoerg }
3287330f729Sjoerg // Check if this is a direct call to a known function or a known
3297330f729Sjoerg // intrinsic, or an indirect call with profile data.
3307330f729Sjoerg if (CalledFunction) {
3317330f729Sjoerg if (CI && CalledFunction->isIntrinsic()) {
3327330f729Sjoerg addIntrinsicToSummary(
3337330f729Sjoerg CI, TypeTests, TypeTestAssumeVCalls, TypeCheckedLoadVCalls,
3347330f729Sjoerg TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls, DT);
3357330f729Sjoerg continue;
3367330f729Sjoerg }
3377330f729Sjoerg // We should have named any anonymous globals
3387330f729Sjoerg assert(CalledFunction->hasName());
339*82d56013Sjoerg auto ScaledCount = PSI->getProfileCount(*CB, BFI);
3407330f729Sjoerg auto Hotness = ScaledCount ? getHotness(ScaledCount.getValue(), PSI)
3417330f729Sjoerg : CalleeInfo::HotnessType::Unknown;
3427330f729Sjoerg if (ForceSummaryEdgesCold != FunctionSummary::FSHT_None)
3437330f729Sjoerg Hotness = CalleeInfo::HotnessType::Cold;
3447330f729Sjoerg
3457330f729Sjoerg // Use the original CalledValue, in case it was an alias. We want
3467330f729Sjoerg // to record the call edge to the alias in that case. Eventually
3477330f729Sjoerg // an alias summary will be created to associate the alias and
3487330f729Sjoerg // aliasee.
3497330f729Sjoerg auto &ValueInfo = CallGraphEdges[Index.getOrInsertValueInfo(
3507330f729Sjoerg cast<GlobalValue>(CalledValue))];
3517330f729Sjoerg ValueInfo.updateHotness(Hotness);
3527330f729Sjoerg // Add the relative block frequency to CalleeInfo if there is no profile
3537330f729Sjoerg // information.
3547330f729Sjoerg if (BFI != nullptr && Hotness == CalleeInfo::HotnessType::Unknown) {
3557330f729Sjoerg uint64_t BBFreq = BFI->getBlockFreq(&BB).getFrequency();
3567330f729Sjoerg uint64_t EntryFreq = BFI->getEntryFreq();
3577330f729Sjoerg ValueInfo.updateRelBlockFreq(BBFreq, EntryFreq);
3587330f729Sjoerg }
3597330f729Sjoerg } else {
3607330f729Sjoerg // Skip inline assembly calls.
3617330f729Sjoerg if (CI && CI->isInlineAsm())
3627330f729Sjoerg continue;
3637330f729Sjoerg // Skip direct calls.
3647330f729Sjoerg if (!CalledValue || isa<Constant>(CalledValue))
3657330f729Sjoerg continue;
3667330f729Sjoerg
3677330f729Sjoerg // Check if the instruction has a callees metadata. If so, add callees
3687330f729Sjoerg // to CallGraphEdges to reflect the references from the metadata, and
3697330f729Sjoerg // to enable importing for subsequent indirect call promotion and
3707330f729Sjoerg // inlining.
3717330f729Sjoerg if (auto *MD = I.getMetadata(LLVMContext::MD_callees)) {
3727330f729Sjoerg for (auto &Op : MD->operands()) {
3737330f729Sjoerg Function *Callee = mdconst::extract_or_null<Function>(Op);
3747330f729Sjoerg if (Callee)
3757330f729Sjoerg CallGraphEdges[Index.getOrInsertValueInfo(Callee)];
3767330f729Sjoerg }
3777330f729Sjoerg }
3787330f729Sjoerg
3797330f729Sjoerg uint32_t NumVals, NumCandidates;
3807330f729Sjoerg uint64_t TotalCount;
3817330f729Sjoerg auto CandidateProfileData =
3827330f729Sjoerg ICallAnalysis.getPromotionCandidatesForInstruction(
3837330f729Sjoerg &I, NumVals, TotalCount, NumCandidates);
3847330f729Sjoerg for (auto &Candidate : CandidateProfileData)
3857330f729Sjoerg CallGraphEdges[Index.getOrInsertValueInfo(Candidate.Value)]
3867330f729Sjoerg .updateHotness(getHotness(Candidate.Count, PSI));
3877330f729Sjoerg }
3887330f729Sjoerg }
389*82d56013Sjoerg Index.addBlockCount(F.size());
3907330f729Sjoerg
3917330f729Sjoerg std::vector<ValueInfo> Refs;
3927330f729Sjoerg if (IsThinLTO) {
3937330f729Sjoerg auto AddRefEdges = [&](const std::vector<const Instruction *> &Instrs,
3947330f729Sjoerg SetVector<ValueInfo> &Edges,
3957330f729Sjoerg SmallPtrSet<const User *, 8> &Cache) {
3967330f729Sjoerg for (const auto *I : Instrs) {
3977330f729Sjoerg Cache.erase(I);
3987330f729Sjoerg findRefEdges(Index, I, Edges, Cache);
3997330f729Sjoerg }
4007330f729Sjoerg };
4017330f729Sjoerg
4027330f729Sjoerg // By now we processed all instructions in a function, except
4037330f729Sjoerg // non-volatile loads and non-volatile value stores. Let's find
4047330f729Sjoerg // ref edges for both of instruction sets
4057330f729Sjoerg AddRefEdges(NonVolatileLoads, LoadRefEdges, Visited);
4067330f729Sjoerg // We can add some values to the Visited set when processing load
4077330f729Sjoerg // instructions which are also used by stores in NonVolatileStores.
4087330f729Sjoerg // For example this can happen if we have following code:
4097330f729Sjoerg //
4107330f729Sjoerg // store %Derived* @foo, %Derived** bitcast (%Base** @bar to %Derived**)
4117330f729Sjoerg // %42 = load %Derived*, %Derived** bitcast (%Base** @bar to %Derived**)
4127330f729Sjoerg //
4137330f729Sjoerg // After processing loads we'll add bitcast to the Visited set, and if
4147330f729Sjoerg // we use the same set while processing stores, we'll never see store
4157330f729Sjoerg // to @bar and @bar will be mistakenly treated as readonly.
4167330f729Sjoerg SmallPtrSet<const llvm::User *, 8> StoreCache;
4177330f729Sjoerg AddRefEdges(NonVolatileStores, StoreRefEdges, StoreCache);
4187330f729Sjoerg
4197330f729Sjoerg // If both load and store instruction reference the same variable
4207330f729Sjoerg // we won't be able to optimize it. Add all such reference edges
4217330f729Sjoerg // to RefEdges set.
4227330f729Sjoerg for (auto &VI : StoreRefEdges)
4237330f729Sjoerg if (LoadRefEdges.remove(VI))
4247330f729Sjoerg RefEdges.insert(VI);
4257330f729Sjoerg
4267330f729Sjoerg unsigned RefCnt = RefEdges.size();
4277330f729Sjoerg // All new reference edges inserted in two loops below are either
4287330f729Sjoerg // read or write only. They will be grouped in the end of RefEdges
4297330f729Sjoerg // vector, so we can use a single integer value to identify them.
4307330f729Sjoerg for (auto &VI : LoadRefEdges)
4317330f729Sjoerg RefEdges.insert(VI);
4327330f729Sjoerg
4337330f729Sjoerg unsigned FirstWORef = RefEdges.size();
4347330f729Sjoerg for (auto &VI : StoreRefEdges)
4357330f729Sjoerg RefEdges.insert(VI);
4367330f729Sjoerg
4377330f729Sjoerg Refs = RefEdges.takeVector();
4387330f729Sjoerg for (; RefCnt < FirstWORef; ++RefCnt)
4397330f729Sjoerg Refs[RefCnt].setReadOnly();
4407330f729Sjoerg
4417330f729Sjoerg for (; RefCnt < Refs.size(); ++RefCnt)
4427330f729Sjoerg Refs[RefCnt].setWriteOnly();
4437330f729Sjoerg } else {
4447330f729Sjoerg Refs = RefEdges.takeVector();
4457330f729Sjoerg }
4467330f729Sjoerg // Explicit add hot edges to enforce importing for designated GUIDs for
4477330f729Sjoerg // sample PGO, to enable the same inlines as the profiled optimized binary.
4487330f729Sjoerg for (auto &I : F.getImportGUIDs())
4497330f729Sjoerg CallGraphEdges[Index.getOrInsertValueInfo(I)].updateHotness(
4507330f729Sjoerg ForceSummaryEdgesCold == FunctionSummary::FSHT_All
4517330f729Sjoerg ? CalleeInfo::HotnessType::Cold
4527330f729Sjoerg : CalleeInfo::HotnessType::Critical);
4537330f729Sjoerg
4547330f729Sjoerg bool NonRenamableLocal = isNonRenamableLocal(F);
4557330f729Sjoerg bool NotEligibleForImport =
4567330f729Sjoerg NonRenamableLocal || HasInlineAsmMaybeReferencingInternal;
457*82d56013Sjoerg GlobalValueSummary::GVFlags Flags(
458*82d56013Sjoerg F.getLinkage(), F.getVisibility(), NotEligibleForImport,
4597330f729Sjoerg /* Live = */ false, F.isDSOLocal(),
4607330f729Sjoerg F.hasLinkOnceODRLinkage() && F.hasGlobalUnnamedAddr());
4617330f729Sjoerg FunctionSummary::FFlags FunFlags{
4627330f729Sjoerg F.hasFnAttribute(Attribute::ReadNone),
4637330f729Sjoerg F.hasFnAttribute(Attribute::ReadOnly),
4647330f729Sjoerg F.hasFnAttribute(Attribute::NoRecurse), F.returnDoesNotAlias(),
4657330f729Sjoerg // FIXME: refactor this to use the same code that inliner is using.
4667330f729Sjoerg // Don't try to import functions with noinline attribute.
467*82d56013Sjoerg F.getAttributes().hasFnAttribute(Attribute::NoInline),
468*82d56013Sjoerg F.hasFnAttribute(Attribute::AlwaysInline)};
469*82d56013Sjoerg std::vector<FunctionSummary::ParamAccess> ParamAccesses;
470*82d56013Sjoerg if (auto *SSI = GetSSICallback(F))
471*82d56013Sjoerg ParamAccesses = SSI->getParamAccesses(Index);
4727330f729Sjoerg auto FuncSummary = std::make_unique<FunctionSummary>(
4737330f729Sjoerg Flags, NumInsts, FunFlags, /*EntryCount=*/0, std::move(Refs),
4747330f729Sjoerg CallGraphEdges.takeVector(), TypeTests.takeVector(),
4757330f729Sjoerg TypeTestAssumeVCalls.takeVector(), TypeCheckedLoadVCalls.takeVector(),
4767330f729Sjoerg TypeTestAssumeConstVCalls.takeVector(),
477*82d56013Sjoerg TypeCheckedLoadConstVCalls.takeVector(), std::move(ParamAccesses));
4787330f729Sjoerg if (NonRenamableLocal)
4797330f729Sjoerg CantBePromoted.insert(F.getGUID());
4807330f729Sjoerg Index.addGlobalValueSummary(F, std::move(FuncSummary));
4817330f729Sjoerg }
4827330f729Sjoerg
4837330f729Sjoerg /// Find function pointers referenced within the given vtable initializer
4847330f729Sjoerg /// (or subset of an initializer) \p I. The starting offset of \p I within
4857330f729Sjoerg /// the vtable initializer is \p StartingOffset. Any discovered function
4867330f729Sjoerg /// pointers are added to \p VTableFuncs along with their cumulative offset
4877330f729Sjoerg /// within the initializer.
findFuncPointers(const Constant * I,uint64_t StartingOffset,const Module & M,ModuleSummaryIndex & Index,VTableFuncList & VTableFuncs)4887330f729Sjoerg static void findFuncPointers(const Constant *I, uint64_t StartingOffset,
4897330f729Sjoerg const Module &M, ModuleSummaryIndex &Index,
4907330f729Sjoerg VTableFuncList &VTableFuncs) {
4917330f729Sjoerg // First check if this is a function pointer.
4927330f729Sjoerg if (I->getType()->isPointerTy()) {
4937330f729Sjoerg auto Fn = dyn_cast<Function>(I->stripPointerCasts());
4947330f729Sjoerg // We can disregard __cxa_pure_virtual as a possible call target, as
4957330f729Sjoerg // calls to pure virtuals are UB.
4967330f729Sjoerg if (Fn && Fn->getName() != "__cxa_pure_virtual")
4977330f729Sjoerg VTableFuncs.push_back({Index.getOrInsertValueInfo(Fn), StartingOffset});
4987330f729Sjoerg return;
4997330f729Sjoerg }
5007330f729Sjoerg
5017330f729Sjoerg // Walk through the elements in the constant struct or array and recursively
5027330f729Sjoerg // look for virtual function pointers.
5037330f729Sjoerg const DataLayout &DL = M.getDataLayout();
5047330f729Sjoerg if (auto *C = dyn_cast<ConstantStruct>(I)) {
5057330f729Sjoerg StructType *STy = dyn_cast<StructType>(C->getType());
5067330f729Sjoerg assert(STy);
5077330f729Sjoerg const StructLayout *SL = DL.getStructLayout(C->getType());
5087330f729Sjoerg
509*82d56013Sjoerg for (auto EI : llvm::enumerate(STy->elements())) {
510*82d56013Sjoerg auto Offset = SL->getElementOffset(EI.index());
5117330f729Sjoerg unsigned Op = SL->getElementContainingOffset(Offset);
5127330f729Sjoerg findFuncPointers(cast<Constant>(I->getOperand(Op)),
5137330f729Sjoerg StartingOffset + Offset, M, Index, VTableFuncs);
5147330f729Sjoerg }
5157330f729Sjoerg } else if (auto *C = dyn_cast<ConstantArray>(I)) {
5167330f729Sjoerg ArrayType *ATy = C->getType();
5177330f729Sjoerg Type *EltTy = ATy->getElementType();
5187330f729Sjoerg uint64_t EltSize = DL.getTypeAllocSize(EltTy);
5197330f729Sjoerg for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
5207330f729Sjoerg findFuncPointers(cast<Constant>(I->getOperand(i)),
5217330f729Sjoerg StartingOffset + i * EltSize, M, Index, VTableFuncs);
5227330f729Sjoerg }
5237330f729Sjoerg }
5247330f729Sjoerg }
5257330f729Sjoerg
5267330f729Sjoerg // Identify the function pointers referenced by vtable definition \p V.
computeVTableFuncs(ModuleSummaryIndex & Index,const GlobalVariable & V,const Module & M,VTableFuncList & VTableFuncs)5277330f729Sjoerg static void computeVTableFuncs(ModuleSummaryIndex &Index,
5287330f729Sjoerg const GlobalVariable &V, const Module &M,
5297330f729Sjoerg VTableFuncList &VTableFuncs) {
5307330f729Sjoerg if (!V.isConstant())
5317330f729Sjoerg return;
5327330f729Sjoerg
5337330f729Sjoerg findFuncPointers(V.getInitializer(), /*StartingOffset=*/0, M, Index,
5347330f729Sjoerg VTableFuncs);
5357330f729Sjoerg
5367330f729Sjoerg #ifndef NDEBUG
5377330f729Sjoerg // Validate that the VTableFuncs list is ordered by offset.
5387330f729Sjoerg uint64_t PrevOffset = 0;
5397330f729Sjoerg for (auto &P : VTableFuncs) {
5407330f729Sjoerg // The findVFuncPointers traversal should have encountered the
5417330f729Sjoerg // functions in offset order. We need to use ">=" since PrevOffset
5427330f729Sjoerg // starts at 0.
5437330f729Sjoerg assert(P.VTableOffset >= PrevOffset);
5447330f729Sjoerg PrevOffset = P.VTableOffset;
5457330f729Sjoerg }
5467330f729Sjoerg #endif
5477330f729Sjoerg }
5487330f729Sjoerg
5497330f729Sjoerg /// Record vtable definition \p V for each type metadata it references.
5507330f729Sjoerg static void
recordTypeIdCompatibleVtableReferences(ModuleSummaryIndex & Index,const GlobalVariable & V,SmallVectorImpl<MDNode * > & Types)5517330f729Sjoerg recordTypeIdCompatibleVtableReferences(ModuleSummaryIndex &Index,
5527330f729Sjoerg const GlobalVariable &V,
5537330f729Sjoerg SmallVectorImpl<MDNode *> &Types) {
5547330f729Sjoerg for (MDNode *Type : Types) {
5557330f729Sjoerg auto TypeID = Type->getOperand(1).get();
5567330f729Sjoerg
5577330f729Sjoerg uint64_t Offset =
5587330f729Sjoerg cast<ConstantInt>(
5597330f729Sjoerg cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
5607330f729Sjoerg ->getZExtValue();
5617330f729Sjoerg
5627330f729Sjoerg if (auto *TypeId = dyn_cast<MDString>(TypeID))
5637330f729Sjoerg Index.getOrInsertTypeIdCompatibleVtableSummary(TypeId->getString())
5647330f729Sjoerg .push_back({Offset, Index.getOrInsertValueInfo(&V)});
5657330f729Sjoerg }
5667330f729Sjoerg }
5677330f729Sjoerg
computeVariableSummary(ModuleSummaryIndex & Index,const GlobalVariable & V,DenseSet<GlobalValue::GUID> & CantBePromoted,const Module & M,SmallVectorImpl<MDNode * > & Types)5687330f729Sjoerg static void computeVariableSummary(ModuleSummaryIndex &Index,
5697330f729Sjoerg const GlobalVariable &V,
5707330f729Sjoerg DenseSet<GlobalValue::GUID> &CantBePromoted,
5717330f729Sjoerg const Module &M,
5727330f729Sjoerg SmallVectorImpl<MDNode *> &Types) {
5737330f729Sjoerg SetVector<ValueInfo> RefEdges;
5747330f729Sjoerg SmallPtrSet<const User *, 8> Visited;
5757330f729Sjoerg bool HasBlockAddress = findRefEdges(Index, &V, RefEdges, Visited);
5767330f729Sjoerg bool NonRenamableLocal = isNonRenamableLocal(V);
577*82d56013Sjoerg GlobalValueSummary::GVFlags Flags(
578*82d56013Sjoerg V.getLinkage(), V.getVisibility(), NonRenamableLocal,
5797330f729Sjoerg /* Live = */ false, V.isDSOLocal(),
5807330f729Sjoerg V.hasLinkOnceODRLinkage() && V.hasGlobalUnnamedAddr());
5817330f729Sjoerg
5827330f729Sjoerg VTableFuncList VTableFuncs;
5837330f729Sjoerg // If splitting is not enabled, then we compute the summary information
5847330f729Sjoerg // necessary for index-based whole program devirtualization.
5857330f729Sjoerg if (!Index.enableSplitLTOUnit()) {
5867330f729Sjoerg Types.clear();
5877330f729Sjoerg V.getMetadata(LLVMContext::MD_type, Types);
5887330f729Sjoerg if (!Types.empty()) {
5897330f729Sjoerg // Identify the function pointers referenced by this vtable definition.
5907330f729Sjoerg computeVTableFuncs(Index, V, M, VTableFuncs);
5917330f729Sjoerg
5927330f729Sjoerg // Record this vtable definition for each type metadata it references.
5937330f729Sjoerg recordTypeIdCompatibleVtableReferences(Index, V, Types);
5947330f729Sjoerg }
5957330f729Sjoerg }
5967330f729Sjoerg
5977330f729Sjoerg // Don't mark variables we won't be able to internalize as read/write-only.
5987330f729Sjoerg bool CanBeInternalized =
5997330f729Sjoerg !V.hasComdat() && !V.hasAppendingLinkage() && !V.isInterposable() &&
6007330f729Sjoerg !V.hasAvailableExternallyLinkage() && !V.hasDLLExportStorageClass();
601*82d56013Sjoerg bool Constant = V.isConstant();
602*82d56013Sjoerg GlobalVarSummary::GVarFlags VarFlags(CanBeInternalized,
603*82d56013Sjoerg Constant ? false : CanBeInternalized,
604*82d56013Sjoerg Constant, V.getVCallVisibility());
6057330f729Sjoerg auto GVarSummary = std::make_unique<GlobalVarSummary>(Flags, VarFlags,
6067330f729Sjoerg RefEdges.takeVector());
6077330f729Sjoerg if (NonRenamableLocal)
6087330f729Sjoerg CantBePromoted.insert(V.getGUID());
6097330f729Sjoerg if (HasBlockAddress)
6107330f729Sjoerg GVarSummary->setNotEligibleToImport();
6117330f729Sjoerg if (!VTableFuncs.empty())
6127330f729Sjoerg GVarSummary->setVTableFuncs(VTableFuncs);
6137330f729Sjoerg Index.addGlobalValueSummary(V, std::move(GVarSummary));
6147330f729Sjoerg }
6157330f729Sjoerg
6167330f729Sjoerg static void
computeAliasSummary(ModuleSummaryIndex & Index,const GlobalAlias & A,DenseSet<GlobalValue::GUID> & CantBePromoted)6177330f729Sjoerg computeAliasSummary(ModuleSummaryIndex &Index, const GlobalAlias &A,
6187330f729Sjoerg DenseSet<GlobalValue::GUID> &CantBePromoted) {
6197330f729Sjoerg bool NonRenamableLocal = isNonRenamableLocal(A);
620*82d56013Sjoerg GlobalValueSummary::GVFlags Flags(
621*82d56013Sjoerg A.getLinkage(), A.getVisibility(), NonRenamableLocal,
6227330f729Sjoerg /* Live = */ false, A.isDSOLocal(),
6237330f729Sjoerg A.hasLinkOnceODRLinkage() && A.hasGlobalUnnamedAddr());
6247330f729Sjoerg auto AS = std::make_unique<AliasSummary>(Flags);
6257330f729Sjoerg auto *Aliasee = A.getBaseObject();
6267330f729Sjoerg auto AliaseeVI = Index.getValueInfo(Aliasee->getGUID());
6277330f729Sjoerg assert(AliaseeVI && "Alias expects aliasee summary to be available");
6287330f729Sjoerg assert(AliaseeVI.getSummaryList().size() == 1 &&
6297330f729Sjoerg "Expected a single entry per aliasee in per-module index");
6307330f729Sjoerg AS->setAliasee(AliaseeVI, AliaseeVI.getSummaryList()[0].get());
6317330f729Sjoerg if (NonRenamableLocal)
6327330f729Sjoerg CantBePromoted.insert(A.getGUID());
6337330f729Sjoerg Index.addGlobalValueSummary(A, std::move(AS));
6347330f729Sjoerg }
6357330f729Sjoerg
6367330f729Sjoerg // Set LiveRoot flag on entries matching the given value name.
setLiveRoot(ModuleSummaryIndex & Index,StringRef Name)6377330f729Sjoerg static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) {
6387330f729Sjoerg if (ValueInfo VI = Index.getValueInfo(GlobalValue::getGUID(Name)))
6397330f729Sjoerg for (auto &Summary : VI.getSummaryList())
6407330f729Sjoerg Summary->setLive(true);
6417330f729Sjoerg }
6427330f729Sjoerg
buildModuleSummaryIndex(const Module & M,std::function<BlockFrequencyInfo * (const Function & F)> GetBFICallback,ProfileSummaryInfo * PSI,std::function<const StackSafetyInfo * (const Function & F)> GetSSICallback)6437330f729Sjoerg ModuleSummaryIndex llvm::buildModuleSummaryIndex(
6447330f729Sjoerg const Module &M,
6457330f729Sjoerg std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback,
646*82d56013Sjoerg ProfileSummaryInfo *PSI,
647*82d56013Sjoerg std::function<const StackSafetyInfo *(const Function &F)> GetSSICallback) {
6487330f729Sjoerg assert(PSI);
6497330f729Sjoerg bool EnableSplitLTOUnit = false;
6507330f729Sjoerg if (auto *MD = mdconst::extract_or_null<ConstantInt>(
6517330f729Sjoerg M.getModuleFlag("EnableSplitLTOUnit")))
6527330f729Sjoerg EnableSplitLTOUnit = MD->getZExtValue();
6537330f729Sjoerg ModuleSummaryIndex Index(/*HaveGVs=*/true, EnableSplitLTOUnit);
6547330f729Sjoerg
6557330f729Sjoerg // Identify the local values in the llvm.used and llvm.compiler.used sets,
6567330f729Sjoerg // which should not be exported as they would then require renaming and
6577330f729Sjoerg // promotion, but we may have opaque uses e.g. in inline asm. We collect them
6587330f729Sjoerg // here because we use this information to mark functions containing inline
6597330f729Sjoerg // assembly calls as not importable.
660*82d56013Sjoerg SmallPtrSet<GlobalValue *, 4> LocalsUsed;
661*82d56013Sjoerg SmallVector<GlobalValue *, 4> Used;
6627330f729Sjoerg // First collect those in the llvm.used set.
663*82d56013Sjoerg collectUsedGlobalVariables(M, Used, /*CompilerUsed=*/false);
6647330f729Sjoerg // Next collect those in the llvm.compiler.used set.
665*82d56013Sjoerg collectUsedGlobalVariables(M, Used, /*CompilerUsed=*/true);
6667330f729Sjoerg DenseSet<GlobalValue::GUID> CantBePromoted;
6677330f729Sjoerg for (auto *V : Used) {
6687330f729Sjoerg if (V->hasLocalLinkage()) {
6697330f729Sjoerg LocalsUsed.insert(V);
6707330f729Sjoerg CantBePromoted.insert(V->getGUID());
6717330f729Sjoerg }
6727330f729Sjoerg }
6737330f729Sjoerg
6747330f729Sjoerg bool HasLocalInlineAsmSymbol = false;
6757330f729Sjoerg if (!M.getModuleInlineAsm().empty()) {
6767330f729Sjoerg // Collect the local values defined by module level asm, and set up
6777330f729Sjoerg // summaries for these symbols so that they can be marked as NoRename,
6787330f729Sjoerg // to prevent export of any use of them in regular IR that would require
6797330f729Sjoerg // renaming within the module level asm. Note we don't need to create a
6807330f729Sjoerg // summary for weak or global defs, as they don't need to be flagged as
6817330f729Sjoerg // NoRename, and defs in module level asm can't be imported anyway.
6827330f729Sjoerg // Also, any values used but not defined within module level asm should
6837330f729Sjoerg // be listed on the llvm.used or llvm.compiler.used global and marked as
6847330f729Sjoerg // referenced from there.
6857330f729Sjoerg ModuleSymbolTable::CollectAsmSymbols(
6867330f729Sjoerg M, [&](StringRef Name, object::BasicSymbolRef::Flags Flags) {
6877330f729Sjoerg // Symbols not marked as Weak or Global are local definitions.
6887330f729Sjoerg if (Flags & (object::BasicSymbolRef::SF_Weak |
6897330f729Sjoerg object::BasicSymbolRef::SF_Global))
6907330f729Sjoerg return;
6917330f729Sjoerg HasLocalInlineAsmSymbol = true;
6927330f729Sjoerg GlobalValue *GV = M.getNamedValue(Name);
6937330f729Sjoerg if (!GV)
6947330f729Sjoerg return;
6957330f729Sjoerg assert(GV->isDeclaration() && "Def in module asm already has definition");
696*82d56013Sjoerg GlobalValueSummary::GVFlags GVFlags(
697*82d56013Sjoerg GlobalValue::InternalLinkage, GlobalValue::DefaultVisibility,
6987330f729Sjoerg /* NotEligibleToImport = */ true,
6997330f729Sjoerg /* Live = */ true,
7007330f729Sjoerg /* Local */ GV->isDSOLocal(),
7017330f729Sjoerg GV->hasLinkOnceODRLinkage() && GV->hasGlobalUnnamedAddr());
7027330f729Sjoerg CantBePromoted.insert(GV->getGUID());
7037330f729Sjoerg // Create the appropriate summary type.
7047330f729Sjoerg if (Function *F = dyn_cast<Function>(GV)) {
7057330f729Sjoerg std::unique_ptr<FunctionSummary> Summary =
7067330f729Sjoerg std::make_unique<FunctionSummary>(
7077330f729Sjoerg GVFlags, /*InstCount=*/0,
7087330f729Sjoerg FunctionSummary::FFlags{
7097330f729Sjoerg F->hasFnAttribute(Attribute::ReadNone),
7107330f729Sjoerg F->hasFnAttribute(Attribute::ReadOnly),
7117330f729Sjoerg F->hasFnAttribute(Attribute::NoRecurse),
7127330f729Sjoerg F->returnDoesNotAlias(),
713*82d56013Sjoerg /* NoInline = */ false,
714*82d56013Sjoerg F->hasFnAttribute(Attribute::AlwaysInline)},
7157330f729Sjoerg /*EntryCount=*/0, ArrayRef<ValueInfo>{},
7167330f729Sjoerg ArrayRef<FunctionSummary::EdgeTy>{},
7177330f729Sjoerg ArrayRef<GlobalValue::GUID>{},
7187330f729Sjoerg ArrayRef<FunctionSummary::VFuncId>{},
7197330f729Sjoerg ArrayRef<FunctionSummary::VFuncId>{},
7207330f729Sjoerg ArrayRef<FunctionSummary::ConstVCall>{},
721*82d56013Sjoerg ArrayRef<FunctionSummary::ConstVCall>{},
722*82d56013Sjoerg ArrayRef<FunctionSummary::ParamAccess>{});
7237330f729Sjoerg Index.addGlobalValueSummary(*GV, std::move(Summary));
7247330f729Sjoerg } else {
7257330f729Sjoerg std::unique_ptr<GlobalVarSummary> Summary =
7267330f729Sjoerg std::make_unique<GlobalVarSummary>(
727*82d56013Sjoerg GVFlags,
728*82d56013Sjoerg GlobalVarSummary::GVarFlags(
729*82d56013Sjoerg false, false, cast<GlobalVariable>(GV)->isConstant(),
730*82d56013Sjoerg GlobalObject::VCallVisibilityPublic),
7317330f729Sjoerg ArrayRef<ValueInfo>{});
7327330f729Sjoerg Index.addGlobalValueSummary(*GV, std::move(Summary));
7337330f729Sjoerg }
7347330f729Sjoerg });
7357330f729Sjoerg }
7367330f729Sjoerg
7377330f729Sjoerg bool IsThinLTO = true;
7387330f729Sjoerg if (auto *MD =
7397330f729Sjoerg mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
7407330f729Sjoerg IsThinLTO = MD->getZExtValue();
7417330f729Sjoerg
7427330f729Sjoerg // Compute summaries for all functions defined in module, and save in the
7437330f729Sjoerg // index.
7447330f729Sjoerg for (auto &F : M) {
7457330f729Sjoerg if (F.isDeclaration())
7467330f729Sjoerg continue;
7477330f729Sjoerg
7487330f729Sjoerg DominatorTree DT(const_cast<Function &>(F));
7497330f729Sjoerg BlockFrequencyInfo *BFI = nullptr;
7507330f729Sjoerg std::unique_ptr<BlockFrequencyInfo> BFIPtr;
7517330f729Sjoerg if (GetBFICallback)
7527330f729Sjoerg BFI = GetBFICallback(F);
7537330f729Sjoerg else if (F.hasProfileData()) {
7547330f729Sjoerg LoopInfo LI{DT};
7557330f729Sjoerg BranchProbabilityInfo BPI{F, LI};
7567330f729Sjoerg BFIPtr = std::make_unique<BlockFrequencyInfo>(F, BPI, LI);
7577330f729Sjoerg BFI = BFIPtr.get();
7587330f729Sjoerg }
7597330f729Sjoerg
7607330f729Sjoerg computeFunctionSummary(Index, M, F, BFI, PSI, DT,
7617330f729Sjoerg !LocalsUsed.empty() || HasLocalInlineAsmSymbol,
762*82d56013Sjoerg CantBePromoted, IsThinLTO, GetSSICallback);
7637330f729Sjoerg }
7647330f729Sjoerg
7657330f729Sjoerg // Compute summaries for all variables defined in module, and save in the
7667330f729Sjoerg // index.
7677330f729Sjoerg SmallVector<MDNode *, 2> Types;
7687330f729Sjoerg for (const GlobalVariable &G : M.globals()) {
7697330f729Sjoerg if (G.isDeclaration())
7707330f729Sjoerg continue;
7717330f729Sjoerg computeVariableSummary(Index, G, CantBePromoted, M, Types);
7727330f729Sjoerg }
7737330f729Sjoerg
7747330f729Sjoerg // Compute summaries for all aliases defined in module, and save in the
7757330f729Sjoerg // index.
7767330f729Sjoerg for (const GlobalAlias &A : M.aliases())
7777330f729Sjoerg computeAliasSummary(Index, A, CantBePromoted);
7787330f729Sjoerg
7797330f729Sjoerg for (auto *V : LocalsUsed) {
7807330f729Sjoerg auto *Summary = Index.getGlobalValueSummary(*V);
7817330f729Sjoerg assert(Summary && "Missing summary for global value");
7827330f729Sjoerg Summary->setNotEligibleToImport();
7837330f729Sjoerg }
7847330f729Sjoerg
7857330f729Sjoerg // The linker doesn't know about these LLVM produced values, so we need
7867330f729Sjoerg // to flag them as live in the index to ensure index-based dead value
7877330f729Sjoerg // analysis treats them as live roots of the analysis.
7887330f729Sjoerg setLiveRoot(Index, "llvm.used");
7897330f729Sjoerg setLiveRoot(Index, "llvm.compiler.used");
7907330f729Sjoerg setLiveRoot(Index, "llvm.global_ctors");
7917330f729Sjoerg setLiveRoot(Index, "llvm.global_dtors");
7927330f729Sjoerg setLiveRoot(Index, "llvm.global.annotations");
7937330f729Sjoerg
7947330f729Sjoerg for (auto &GlobalList : Index) {
7957330f729Sjoerg // Ignore entries for references that are undefined in the current module.
7967330f729Sjoerg if (GlobalList.second.SummaryList.empty())
7977330f729Sjoerg continue;
7987330f729Sjoerg
7997330f729Sjoerg assert(GlobalList.second.SummaryList.size() == 1 &&
8007330f729Sjoerg "Expected module's index to have one summary per GUID");
8017330f729Sjoerg auto &Summary = GlobalList.second.SummaryList[0];
8027330f729Sjoerg if (!IsThinLTO) {
8037330f729Sjoerg Summary->setNotEligibleToImport();
8047330f729Sjoerg continue;
8057330f729Sjoerg }
8067330f729Sjoerg
8077330f729Sjoerg bool AllRefsCanBeExternallyReferenced =
8087330f729Sjoerg llvm::all_of(Summary->refs(), [&](const ValueInfo &VI) {
8097330f729Sjoerg return !CantBePromoted.count(VI.getGUID());
8107330f729Sjoerg });
8117330f729Sjoerg if (!AllRefsCanBeExternallyReferenced) {
8127330f729Sjoerg Summary->setNotEligibleToImport();
8137330f729Sjoerg continue;
8147330f729Sjoerg }
8157330f729Sjoerg
8167330f729Sjoerg if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
8177330f729Sjoerg bool AllCallsCanBeExternallyReferenced = llvm::all_of(
8187330f729Sjoerg FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
8197330f729Sjoerg return !CantBePromoted.count(Edge.first.getGUID());
8207330f729Sjoerg });
8217330f729Sjoerg if (!AllCallsCanBeExternallyReferenced)
8227330f729Sjoerg Summary->setNotEligibleToImport();
8237330f729Sjoerg }
8247330f729Sjoerg }
8257330f729Sjoerg
8267330f729Sjoerg if (!ModuleSummaryDotFile.empty()) {
8277330f729Sjoerg std::error_code EC;
8287330f729Sjoerg raw_fd_ostream OSDot(ModuleSummaryDotFile, EC, sys::fs::OpenFlags::OF_None);
8297330f729Sjoerg if (EC)
8307330f729Sjoerg report_fatal_error(Twine("Failed to open dot file ") +
8317330f729Sjoerg ModuleSummaryDotFile + ": " + EC.message() + "\n");
832*82d56013Sjoerg Index.exportToDot(OSDot, {});
8337330f729Sjoerg }
8347330f729Sjoerg
8357330f729Sjoerg return Index;
8367330f729Sjoerg }
8377330f729Sjoerg
8387330f729Sjoerg AnalysisKey ModuleSummaryIndexAnalysis::Key;
8397330f729Sjoerg
8407330f729Sjoerg ModuleSummaryIndex
run(Module & M,ModuleAnalysisManager & AM)8417330f729Sjoerg ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
8427330f729Sjoerg ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
8437330f729Sjoerg auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
844*82d56013Sjoerg bool NeedSSI = needsParamAccessSummary(M);
8457330f729Sjoerg return buildModuleSummaryIndex(
8467330f729Sjoerg M,
8477330f729Sjoerg [&FAM](const Function &F) {
8487330f729Sjoerg return &FAM.getResult<BlockFrequencyAnalysis>(
8497330f729Sjoerg *const_cast<Function *>(&F));
8507330f729Sjoerg },
851*82d56013Sjoerg &PSI,
852*82d56013Sjoerg [&FAM, NeedSSI](const Function &F) -> const StackSafetyInfo * {
853*82d56013Sjoerg return NeedSSI ? &FAM.getResult<StackSafetyAnalysis>(
854*82d56013Sjoerg const_cast<Function &>(F))
855*82d56013Sjoerg : nullptr;
856*82d56013Sjoerg });
8577330f729Sjoerg }
8587330f729Sjoerg
8597330f729Sjoerg char ModuleSummaryIndexWrapperPass::ID = 0;
8607330f729Sjoerg
8617330f729Sjoerg INITIALIZE_PASS_BEGIN(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
8627330f729Sjoerg "Module Summary Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)8637330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
8647330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
865*82d56013Sjoerg INITIALIZE_PASS_DEPENDENCY(StackSafetyInfoWrapperPass)
8667330f729Sjoerg INITIALIZE_PASS_END(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
8677330f729Sjoerg "Module Summary Analysis", false, true)
8687330f729Sjoerg
8697330f729Sjoerg ModulePass *llvm::createModuleSummaryIndexWrapperPass() {
8707330f729Sjoerg return new ModuleSummaryIndexWrapperPass();
8717330f729Sjoerg }
8727330f729Sjoerg
ModuleSummaryIndexWrapperPass()8737330f729Sjoerg ModuleSummaryIndexWrapperPass::ModuleSummaryIndexWrapperPass()
8747330f729Sjoerg : ModulePass(ID) {
8757330f729Sjoerg initializeModuleSummaryIndexWrapperPassPass(*PassRegistry::getPassRegistry());
8767330f729Sjoerg }
8777330f729Sjoerg
runOnModule(Module & M)8787330f729Sjoerg bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) {
8797330f729Sjoerg auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
880*82d56013Sjoerg bool NeedSSI = needsParamAccessSummary(M);
8817330f729Sjoerg Index.emplace(buildModuleSummaryIndex(
8827330f729Sjoerg M,
8837330f729Sjoerg [this](const Function &F) {
8847330f729Sjoerg return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>(
8857330f729Sjoerg *const_cast<Function *>(&F))
8867330f729Sjoerg .getBFI());
8877330f729Sjoerg },
888*82d56013Sjoerg PSI,
889*82d56013Sjoerg [&](const Function &F) -> const StackSafetyInfo * {
890*82d56013Sjoerg return NeedSSI ? &getAnalysis<StackSafetyInfoWrapperPass>(
891*82d56013Sjoerg const_cast<Function &>(F))
892*82d56013Sjoerg .getResult()
893*82d56013Sjoerg : nullptr;
894*82d56013Sjoerg }));
8957330f729Sjoerg return false;
8967330f729Sjoerg }
8977330f729Sjoerg
doFinalization(Module & M)8987330f729Sjoerg bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) {
8997330f729Sjoerg Index.reset();
9007330f729Sjoerg return false;
9017330f729Sjoerg }
9027330f729Sjoerg
getAnalysisUsage(AnalysisUsage & AU) const9037330f729Sjoerg void ModuleSummaryIndexWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
9047330f729Sjoerg AU.setPreservesAll();
9057330f729Sjoerg AU.addRequired<BlockFrequencyInfoWrapperPass>();
9067330f729Sjoerg AU.addRequired<ProfileSummaryInfoWrapperPass>();
907*82d56013Sjoerg AU.addRequired<StackSafetyInfoWrapperPass>();
9087330f729Sjoerg }
909*82d56013Sjoerg
910*82d56013Sjoerg char ImmutableModuleSummaryIndexWrapperPass::ID = 0;
911*82d56013Sjoerg
ImmutableModuleSummaryIndexWrapperPass(const ModuleSummaryIndex * Index)912*82d56013Sjoerg ImmutableModuleSummaryIndexWrapperPass::ImmutableModuleSummaryIndexWrapperPass(
913*82d56013Sjoerg const ModuleSummaryIndex *Index)
914*82d56013Sjoerg : ImmutablePass(ID), Index(Index) {
915*82d56013Sjoerg initializeImmutableModuleSummaryIndexWrapperPassPass(
916*82d56013Sjoerg *PassRegistry::getPassRegistry());
917*82d56013Sjoerg }
918*82d56013Sjoerg
getAnalysisUsage(AnalysisUsage & AU) const919*82d56013Sjoerg void ImmutableModuleSummaryIndexWrapperPass::getAnalysisUsage(
920*82d56013Sjoerg AnalysisUsage &AU) const {
921*82d56013Sjoerg AU.setPreservesAll();
922*82d56013Sjoerg }
923*82d56013Sjoerg
createImmutableModuleSummaryIndexWrapperPass(const ModuleSummaryIndex * Index)924*82d56013Sjoerg ImmutablePass *llvm::createImmutableModuleSummaryIndexWrapperPass(
925*82d56013Sjoerg const ModuleSummaryIndex *Index) {
926*82d56013Sjoerg return new ImmutableModuleSummaryIndexWrapperPass(Index);
927*82d56013Sjoerg }
928*82d56013Sjoerg
929*82d56013Sjoerg INITIALIZE_PASS(ImmutableModuleSummaryIndexWrapperPass, "module-summary-info",
930*82d56013Sjoerg "Module summary info", false, true)
931