Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp
35269 views
//===- IndirectCallPromotion.cpp - Optimizations based on value profiling -===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the transformation that promotes indirect calls to9// conditional direct calls when the indirect-call value profile metadata is10// available.11//12//===----------------------------------------------------------------------===//1314#include "llvm/ADT/ArrayRef.h"15#include "llvm/ADT/DenseMap.h"16#include "llvm/ADT/Statistic.h"17#include "llvm/ADT/StringRef.h"18#include "llvm/Analysis/IndirectCallPromotionAnalysis.h"19#include "llvm/Analysis/IndirectCallVisitor.h"20#include "llvm/Analysis/OptimizationRemarkEmitter.h"21#include "llvm/Analysis/ProfileSummaryInfo.h"22#include "llvm/Analysis/TypeMetadataUtils.h"23#include "llvm/IR/DiagnosticInfo.h"24#include "llvm/IR/Dominators.h"25#include "llvm/IR/Function.h"26#include "llvm/IR/InstrTypes.h"27#include "llvm/IR/Instructions.h"28#include "llvm/IR/LLVMContext.h"29#include "llvm/IR/MDBuilder.h"30#include "llvm/IR/PassManager.h"31#include "llvm/IR/ProfDataUtils.h"32#include "llvm/IR/Value.h"33#include "llvm/ProfileData/InstrProf.h"34#include "llvm/Support/Casting.h"35#include "llvm/Support/CommandLine.h"36#include "llvm/Support/Debug.h"37#include "llvm/Support/Error.h"38#include "llvm/Support/raw_ostream.h"39#include "llvm/Transforms/Instrumentation.h"40#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"41#include "llvm/Transforms/Utils/CallPromotionUtils.h"42#include <cassert>43#include <cstdint>44#include <memory>45#include <set>46#include <string>47#include <unordered_map>48#include <utility>49#include <vector>5051using namespace llvm;5253#define DEBUG_TYPE "pgo-icall-prom"5455STATISTIC(NumOfPGOICallPromotion, "Number of indirect call promotions.");56STATISTIC(NumOfPGOICallsites, "Number of indirect call candidate sites.");5758extern cl::opt<unsigned> MaxNumVTableAnnotations;5960namespace llvm {61extern cl::opt<bool> EnableVTableProfileUse;62}6364// Command line option to disable indirect-call promotion with the default as65// false. This is for debug purpose.66static cl::opt<bool> DisableICP("disable-icp", cl::init(false), cl::Hidden,67cl::desc("Disable indirect call promotion"));6869// Set the cutoff value for the promotion. If the value is other than 0, we70// stop the transformation once the total number of promotions equals the cutoff71// value.72// For debug use only.73static cl::opt<unsigned>74ICPCutOff("icp-cutoff", cl::init(0), cl::Hidden,75cl::desc("Max number of promotions for this compilation"));7677// If ICPCSSkip is non zero, the first ICPCSSkip callsites will be skipped.78// For debug use only.79static cl::opt<unsigned>80ICPCSSkip("icp-csskip", cl::init(0), cl::Hidden,81cl::desc("Skip Callsite up to this number for this compilation"));8283// Set if the pass is called in LTO optimization. The difference for LTO mode84// is the pass won't prefix the source module name to the internal linkage85// symbols.86static cl::opt<bool> ICPLTOMode("icp-lto", cl::init(false), cl::Hidden,87cl::desc("Run indirect-call promotion in LTO "88"mode"));8990// Set if the pass is called in SamplePGO mode. The difference for SamplePGO91// mode is it will add prof metadatato the created direct call.92static cl::opt<bool>93ICPSamplePGOMode("icp-samplepgo", cl::init(false), cl::Hidden,94cl::desc("Run indirect-call promotion in SamplePGO mode"));9596// If the option is set to true, only call instructions will be considered for97// transformation -- invoke instructions will be ignored.98static cl::opt<bool>99ICPCallOnly("icp-call-only", cl::init(false), cl::Hidden,100cl::desc("Run indirect-call promotion for call instructions "101"only"));102103// If the option is set to true, only invoke instructions will be considered for104// transformation -- call instructions will be ignored.105static cl::opt<bool> ICPInvokeOnly("icp-invoke-only", cl::init(false),106cl::Hidden,107cl::desc("Run indirect-call promotion for "108"invoke instruction only"));109110// Dump the function level IR if the transformation happened in this111// function. For debug use only.112static cl::opt<bool>113ICPDUMPAFTER("icp-dumpafter", cl::init(false), cl::Hidden,114cl::desc("Dump IR after transformation happens"));115116// Indirect call promotion pass will fall back to function-based comparison if117// vtable-count / function-count is smaller than this threshold.118static cl::opt<float> ICPVTablePercentageThreshold(119"icp-vtable-percentage-threshold", cl::init(0.99), cl::Hidden,120cl::desc("The percentage threshold of vtable-count / function-count for "121"cost-benefit analysis."));122123// Although comparing vtables can save a vtable load, we may need to compare124// vtable pointer with multiple vtable address points due to class inheritance.125// Comparing with multiple vtables inserts additional instructions on hot code126// path, and doing so for an earlier candidate delays the comparisons for later127// candidates. For the last candidate, only the fallback path is affected.128// We allow multiple vtable comparison for the last function candidate and use129// the option below to cap the number of vtables.130static cl::opt<int> ICPMaxNumVTableLastCandidate(131"icp-max-num-vtable-last-candidate", cl::init(1), cl::Hidden,132cl::desc("The maximum number of vtable for the last candidate."));133134namespace {135136// The key is a vtable global variable, and the value is a map.137// In the inner map, the key represents address point offsets and the value is a138// constant for this address point.139using VTableAddressPointOffsetValMap =140SmallDenseMap<const GlobalVariable *, std::unordered_map<int, Constant *>>;141142// A struct to collect type information for a virtual call site.143struct VirtualCallSiteInfo {144// The offset from the address point to virtual function in the vtable.145uint64_t FunctionOffset;146// The instruction that computes the address point of vtable.147Instruction *VPtr;148// The compatible type used in LLVM type intrinsics.149StringRef CompatibleTypeStr;150};151152// The key is a virtual call, and value is its type information.153using VirtualCallSiteTypeInfoMap =154SmallDenseMap<const CallBase *, VirtualCallSiteInfo>;155156// The key is vtable GUID, and value is its value profile count.157using VTableGUIDCountsMap = SmallDenseMap<uint64_t, uint64_t, 16>;158159// Return the address point offset of the given compatible type.160//161// Type metadata of a vtable specifies the types that can contain a pointer to162// this vtable, for example, `Base*` can be a pointer to an derived type163// but not vice versa. See also https://llvm.org/docs/TypeMetadata.html164static std::optional<uint64_t>165getAddressPointOffset(const GlobalVariable &VTableVar,166StringRef CompatibleType) {167SmallVector<MDNode *> Types;168VTableVar.getMetadata(LLVMContext::MD_type, Types);169170for (MDNode *Type : Types)171if (auto *TypeId = dyn_cast<MDString>(Type->getOperand(1).get());172TypeId && TypeId->getString() == CompatibleType)173return cast<ConstantInt>(174cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())175->getZExtValue();176177return std::nullopt;178}179180// Return a constant representing the vtable's address point specified by the181// offset.182static Constant *getVTableAddressPointOffset(GlobalVariable *VTable,183uint32_t AddressPointOffset) {184Module &M = *VTable->getParent();185LLVMContext &Context = M.getContext();186assert(AddressPointOffset <187M.getDataLayout().getTypeAllocSize(VTable->getValueType()) &&188"Out-of-bound access");189190return ConstantExpr::getInBoundsGetElementPtr(191Type::getInt8Ty(Context), VTable,192llvm::ConstantInt::get(Type::getInt32Ty(Context), AddressPointOffset));193}194195// Return the basic block in which Use `U` is used via its `UserInst`.196static BasicBlock *getUserBasicBlock(Use &U, Instruction *UserInst) {197if (PHINode *PN = dyn_cast<PHINode>(UserInst))198return PN->getIncomingBlock(U);199200return UserInst->getParent();201}202203// `DestBB` is a suitable basic block to sink `Inst` into when `Inst` have users204// and all users are in `DestBB`. The caller guarantees that `Inst->getParent()`205// is the sole predecessor of `DestBB` and `DestBB` is dominated by206// `Inst->getParent()`.207static bool isDestBBSuitableForSink(Instruction *Inst, BasicBlock *DestBB) {208// 'BB' is used only by assert.209[[maybe_unused]] BasicBlock *BB = Inst->getParent();210211assert(BB != DestBB && BB->getTerminator()->getNumSuccessors() == 2 &&212DestBB->getUniquePredecessor() == BB &&213"Guaranteed by ICP transformation");214215BasicBlock *UserBB = nullptr;216for (Use &Use : Inst->uses()) {217User *User = Use.getUser();218// Do checked cast since IR verifier guarantees that the user of an219// instruction must be an instruction. See `Verifier::visitInstruction`.220Instruction *UserInst = cast<Instruction>(User);221// We can sink debug or pseudo instructions together with Inst.222if (UserInst->isDebugOrPseudoInst())223continue;224UserBB = getUserBasicBlock(Use, UserInst);225// Do not sink if Inst is used in a basic block that is not DestBB.226// TODO: Sink to the common dominator of all user blocks.227if (UserBB != DestBB)228return false;229}230return UserBB != nullptr;231}232233// For the virtual call dispatch sequence, try to sink vtable load instructions234// to the cold indirect call fallback.235// FIXME: Move the sink eligibility check below to a utility function in236// Transforms/Utils/ directory.237static bool tryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {238if (!isDestBBSuitableForSink(I, DestBlock))239return false;240241// Do not move control-flow-involving, volatile loads, vaarg, alloca242// instructions, etc.243if (isa<PHINode>(I) || I->isEHPad() || I->mayThrow() || !I->willReturn() ||244isa<AllocaInst>(I))245return false;246247// Do not sink convergent call instructions.248if (const auto *C = dyn_cast<CallBase>(I))249if (C->isInlineAsm() || C->cannotMerge() || C->isConvergent())250return false;251252// Do not move an instruction that may write to memory.253if (I->mayWriteToMemory())254return false;255256// We can only sink load instructions if there is nothing between the load and257// the end of block that could change the value.258if (I->mayReadFromMemory()) {259// We already know that SrcBlock is the unique predecessor of DestBlock.260for (BasicBlock::iterator Scan = std::next(I->getIterator()),261E = I->getParent()->end();262Scan != E; ++Scan) {263// Note analysis analysis can tell whether two pointers can point to the264// same object in memory or not thereby find further opportunities to265// sink.266if (Scan->mayWriteToMemory())267return false;268}269}270271BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();272I->moveBefore(*DestBlock, InsertPos);273274// TODO: Sink debug intrinsic users of I to 'DestBlock'.275// 'InstCombinerImpl::tryToSinkInstructionDbgValues' and276// 'InstCombinerImpl::tryToSinkInstructionDbgVariableRecords' already have277// the core logic to do this.278return true;279}280281// Try to sink instructions after VPtr to the indirect call fallback.282// Return the number of sunk IR instructions.283static int tryToSinkInstructions(BasicBlock *OriginalBB,284BasicBlock *IndirectCallBB) {285int SinkCount = 0;286// Do not sink across a critical edge for simplicity.287if (IndirectCallBB->getUniquePredecessor() != OriginalBB)288return SinkCount;289// Sink all eligible instructions in OriginalBB in reverse order.290for (Instruction &I :291llvm::make_early_inc_range(llvm::drop_begin(llvm::reverse(*OriginalBB))))292if (tryToSinkInstruction(&I, IndirectCallBB))293SinkCount++;294295return SinkCount;296}297298// Promote indirect calls to conditional direct calls, keeping track of299// thresholds.300class IndirectCallPromoter {301private:302Function &F;303Module &M;304305ProfileSummaryInfo *PSI = nullptr;306307// Symtab that maps indirect call profile values to function names and308// defines.309InstrProfSymtab *const Symtab;310311const bool SamplePGO;312313// A map from a virtual call to its type information.314const VirtualCallSiteTypeInfoMap &VirtualCSInfo;315316VTableAddressPointOffsetValMap &VTableAddressPointOffsetVal;317318OptimizationRemarkEmitter &ORE;319320// A struct that records the direct target and it's call count.321struct PromotionCandidate {322Function *const TargetFunction;323const uint64_t Count;324325// The following fields only exists for promotion candidates with vtable326// information.327//328// Due to class inheritance, one virtual call candidate can come from329// multiple vtables. `VTableGUIDAndCounts` tracks the vtable GUIDs and330// counts for 'TargetFunction'. `AddressPoints` stores the vtable address331// points for comparison.332VTableGUIDCountsMap VTableGUIDAndCounts;333SmallVector<Constant *> AddressPoints;334335PromotionCandidate(Function *F, uint64_t C) : TargetFunction(F), Count(C) {}336};337338// Check if the indirect-call call site should be promoted. Return the number339// of promotions. Inst is the candidate indirect call, ValueDataRef340// contains the array of value profile data for profiled targets,341// TotalCount is the total profiled count of call executions, and342// NumCandidates is the number of candidate entries in ValueDataRef.343std::vector<PromotionCandidate> getPromotionCandidatesForCallSite(344const CallBase &CB, ArrayRef<InstrProfValueData> ValueDataRef,345uint64_t TotalCount, uint32_t NumCandidates);346347// Promote a list of targets for one indirect-call callsite by comparing348// indirect callee with functions. Return true if there are IR349// transformations and false otherwise.350bool tryToPromoteWithFuncCmp(CallBase &CB, Instruction *VPtr,351ArrayRef<PromotionCandidate> Candidates,352uint64_t TotalCount,353ArrayRef<InstrProfValueData> ICallProfDataRef,354uint32_t NumCandidates,355VTableGUIDCountsMap &VTableGUIDCounts);356357// Promote a list of targets for one indirect call by comparing vtables with358// functions. Return true if there are IR transformations and false359// otherwise.360bool tryToPromoteWithVTableCmp(361CallBase &CB, Instruction *VPtr, ArrayRef<PromotionCandidate> Candidates,362uint64_t TotalFuncCount, uint32_t NumCandidates,363MutableArrayRef<InstrProfValueData> ICallProfDataRef,364VTableGUIDCountsMap &VTableGUIDCounts);365366// Return true if it's profitable to compare vtables for the callsite.367bool isProfitableToCompareVTables(const CallBase &CB,368ArrayRef<PromotionCandidate> Candidates,369uint64_t TotalCount);370371// Given an indirect callsite and the list of function candidates, compute372// the following vtable information in output parameters and return vtable373// pointer if type profiles exist.374// - Populate `VTableGUIDCounts` with <vtable-guid, count> using !prof375// metadata attached on the vtable pointer.376// - For each function candidate, finds out the vtables from which it gets377// called and stores the <vtable-guid, count> in promotion candidate.378Instruction *computeVTableInfos(const CallBase *CB,379VTableGUIDCountsMap &VTableGUIDCounts,380std::vector<PromotionCandidate> &Candidates);381382Constant *getOrCreateVTableAddressPointVar(GlobalVariable *GV,383uint64_t AddressPointOffset);384385void updateFuncValueProfiles(CallBase &CB, ArrayRef<InstrProfValueData> VDs,386uint64_t Sum, uint32_t MaxMDCount);387388void updateVPtrValueProfiles(Instruction *VPtr,389VTableGUIDCountsMap &VTableGUIDCounts);390391public:392IndirectCallPromoter(393Function &Func, Module &M, ProfileSummaryInfo *PSI,394InstrProfSymtab *Symtab, bool SamplePGO,395const VirtualCallSiteTypeInfoMap &VirtualCSInfo,396VTableAddressPointOffsetValMap &VTableAddressPointOffsetVal,397OptimizationRemarkEmitter &ORE)398: F(Func), M(M), PSI(PSI), Symtab(Symtab), SamplePGO(SamplePGO),399VirtualCSInfo(VirtualCSInfo),400VTableAddressPointOffsetVal(VTableAddressPointOffsetVal), ORE(ORE) {}401IndirectCallPromoter(const IndirectCallPromoter &) = delete;402IndirectCallPromoter &operator=(const IndirectCallPromoter &) = delete;403404bool processFunction(ProfileSummaryInfo *PSI);405};406407} // end anonymous namespace408409// Indirect-call promotion heuristic. The direct targets are sorted based on410// the count. Stop at the first target that is not promoted.411std::vector<IndirectCallPromoter::PromotionCandidate>412IndirectCallPromoter::getPromotionCandidatesForCallSite(413const CallBase &CB, ArrayRef<InstrProfValueData> ValueDataRef,414uint64_t TotalCount, uint32_t NumCandidates) {415std::vector<PromotionCandidate> Ret;416417LLVM_DEBUG(dbgs() << " \nWork on callsite #" << NumOfPGOICallsites << CB418<< " Num_targets: " << ValueDataRef.size()419<< " Num_candidates: " << NumCandidates << "\n");420NumOfPGOICallsites++;421if (ICPCSSkip != 0 && NumOfPGOICallsites <= ICPCSSkip) {422LLVM_DEBUG(dbgs() << " Skip: User options.\n");423return Ret;424}425426for (uint32_t I = 0; I < NumCandidates; I++) {427uint64_t Count = ValueDataRef[I].Count;428assert(Count <= TotalCount);429(void)TotalCount;430uint64_t Target = ValueDataRef[I].Value;431LLVM_DEBUG(dbgs() << " Candidate " << I << " Count=" << Count432<< " Target_func: " << Target << "\n");433434if (ICPInvokeOnly && isa<CallInst>(CB)) {435LLVM_DEBUG(dbgs() << " Not promote: User options.\n");436ORE.emit([&]() {437return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", &CB)438<< " Not promote: User options";439});440break;441}442if (ICPCallOnly && isa<InvokeInst>(CB)) {443LLVM_DEBUG(dbgs() << " Not promote: User option.\n");444ORE.emit([&]() {445return OptimizationRemarkMissed(DEBUG_TYPE, "UserOptions", &CB)446<< " Not promote: User options";447});448break;449}450if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {451LLVM_DEBUG(dbgs() << " Not promote: Cutoff reached.\n");452ORE.emit([&]() {453return OptimizationRemarkMissed(DEBUG_TYPE, "CutOffReached", &CB)454<< " Not promote: Cutoff reached";455});456break;457}458459// Don't promote if the symbol is not defined in the module. This avoids460// creating a reference to a symbol that doesn't exist in the module461// This can happen when we compile with a sample profile collected from462// one binary but used for another, which may have profiled targets that463// aren't used in the new binary. We might have a declaration initially in464// the case where the symbol is globally dead in the binary and removed by465// ThinLTO.466Function *TargetFunction = Symtab->getFunction(Target);467if (TargetFunction == nullptr || TargetFunction->isDeclaration()) {468LLVM_DEBUG(dbgs() << " Not promote: Cannot find the target\n");469ORE.emit([&]() {470return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToFindTarget", &CB)471<< "Cannot promote indirect call: target with md5sum "472<< ore::NV("target md5sum", Target) << " not found";473});474break;475}476477const char *Reason = nullptr;478if (!isLegalToPromote(CB, TargetFunction, &Reason)) {479using namespace ore;480481ORE.emit([&]() {482return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToPromote", &CB)483<< "Cannot promote indirect call to "484<< NV("TargetFunction", TargetFunction) << " with count of "485<< NV("Count", Count) << ": " << Reason;486});487break;488}489490Ret.push_back(PromotionCandidate(TargetFunction, Count));491TotalCount -= Count;492}493return Ret;494}495496Constant *IndirectCallPromoter::getOrCreateVTableAddressPointVar(497GlobalVariable *GV, uint64_t AddressPointOffset) {498auto [Iter, Inserted] =499VTableAddressPointOffsetVal[GV].try_emplace(AddressPointOffset, nullptr);500if (Inserted)501Iter->second = getVTableAddressPointOffset(GV, AddressPointOffset);502return Iter->second;503}504505Instruction *IndirectCallPromoter::computeVTableInfos(506const CallBase *CB, VTableGUIDCountsMap &GUIDCountsMap,507std::vector<PromotionCandidate> &Candidates) {508if (!EnableVTableProfileUse)509return nullptr;510511// Take the following code sequence as an example, here is how the code works512// @vtable1 = {[n x ptr] [... ptr @func1]}513// @vtable2 = {[m x ptr] [... ptr @func2]}514//515// %vptr = load ptr, ptr %d, !prof !0516// %0 = tail call i1 @llvm.type.test(ptr %vptr, metadata !"vtable1")517// tail call void @llvm.assume(i1 %0)518// %vfn = getelementptr inbounds ptr, ptr %vptr, i64 1519// %1 = load ptr, ptr %vfn520// call void %1(ptr %d), !prof !1521//522// !0 = !{!"VP", i32 2, i64 100, i64 123, i64 50, i64 456, i64 50}523// !1 = !{!"VP", i32 0, i64 100, i64 789, i64 50, i64 579, i64 50}524//525// Step 1. Find out the %vptr instruction for indirect call and use its !prof526// to populate `GUIDCountsMap`.527// Step 2. For each vtable-guid, look up its definition from symtab. LTO can528// make vtable definitions visible across modules.529// Step 3. Compute the byte offset of the virtual call, by adding vtable530// address point offset and function's offset relative to vtable address531// point. For each function candidate, this step tells us the vtable from532// which it comes from, and the vtable address point to compare %vptr with.533534// Only virtual calls have virtual call site info.535auto Iter = VirtualCSInfo.find(CB);536if (Iter == VirtualCSInfo.end())537return nullptr;538539LLVM_DEBUG(dbgs() << "\nComputing vtable infos for callsite #"540<< NumOfPGOICallsites << "\n");541542const auto &VirtualCallInfo = Iter->second;543Instruction *VPtr = VirtualCallInfo.VPtr;544545SmallDenseMap<Function *, int, 4> CalleeIndexMap;546for (size_t I = 0; I < Candidates.size(); I++)547CalleeIndexMap[Candidates[I].TargetFunction] = I;548549uint64_t TotalVTableCount = 0;550auto VTableValueDataArray =551getValueProfDataFromInst(*VirtualCallInfo.VPtr, IPVK_VTableTarget,552MaxNumVTableAnnotations, TotalVTableCount);553if (VTableValueDataArray.empty())554return VPtr;555556// Compute the functions and counts from by each vtable.557for (const auto &V : VTableValueDataArray) {558uint64_t VTableVal = V.Value;559GUIDCountsMap[VTableVal] = V.Count;560GlobalVariable *VTableVar = Symtab->getGlobalVariable(VTableVal);561if (!VTableVar) {562LLVM_DEBUG(dbgs() << " Cannot find vtable definition for " << VTableVal563<< "; maybe the vtable isn't imported\n");564continue;565}566567std::optional<uint64_t> MaybeAddressPointOffset =568getAddressPointOffset(*VTableVar, VirtualCallInfo.CompatibleTypeStr);569if (!MaybeAddressPointOffset)570continue;571572const uint64_t AddressPointOffset = *MaybeAddressPointOffset;573574Function *Callee = nullptr;575std::tie(Callee, std::ignore) = getFunctionAtVTableOffset(576VTableVar, AddressPointOffset + VirtualCallInfo.FunctionOffset, M);577if (!Callee)578continue;579auto CalleeIndexIter = CalleeIndexMap.find(Callee);580if (CalleeIndexIter == CalleeIndexMap.end())581continue;582583auto &Candidate = Candidates[CalleeIndexIter->second];584// There shouldn't be duplicate GUIDs in one !prof metadata (except585// duplicated zeros), so assign counters directly won't cause overwrite or586// counter loss.587Candidate.VTableGUIDAndCounts[VTableVal] = V.Count;588Candidate.AddressPoints.push_back(589getOrCreateVTableAddressPointVar(VTableVar, AddressPointOffset));590}591592return VPtr;593}594595// Creates 'branch_weights' prof metadata using TrueWeight and FalseWeight.596// Scales uint64_t counters down to uint32_t if necessary to prevent overflow.597static MDNode *createBranchWeights(LLVMContext &Context, uint64_t TrueWeight,598uint64_t FalseWeight) {599MDBuilder MDB(Context);600uint64_t Scale = calculateCountScale(std::max(TrueWeight, FalseWeight));601return MDB.createBranchWeights(scaleBranchCount(TrueWeight, Scale),602scaleBranchCount(FalseWeight, Scale));603}604605CallBase &llvm::pgo::promoteIndirectCall(CallBase &CB, Function *DirectCallee,606uint64_t Count, uint64_t TotalCount,607bool AttachProfToDirectCall,608OptimizationRemarkEmitter *ORE) {609CallBase &NewInst = promoteCallWithIfThenElse(610CB, DirectCallee,611createBranchWeights(CB.getContext(), Count, TotalCount - Count));612613if (AttachProfToDirectCall)614setBranchWeights(NewInst, {static_cast<uint32_t>(Count)},615/*IsExpected=*/false);616617using namespace ore;618619if (ORE)620ORE->emit([&]() {621return OptimizationRemark(DEBUG_TYPE, "Promoted", &CB)622<< "Promote indirect call to " << NV("DirectCallee", DirectCallee)623<< " with count " << NV("Count", Count) << " out of "624<< NV("TotalCount", TotalCount);625});626return NewInst;627}628629// Promote indirect-call to conditional direct-call for one callsite.630bool IndirectCallPromoter::tryToPromoteWithFuncCmp(631CallBase &CB, Instruction *VPtr, ArrayRef<PromotionCandidate> Candidates,632uint64_t TotalCount, ArrayRef<InstrProfValueData> ICallProfDataRef,633uint32_t NumCandidates, VTableGUIDCountsMap &VTableGUIDCounts) {634uint32_t NumPromoted = 0;635636for (const auto &C : Candidates) {637uint64_t FuncCount = C.Count;638pgo::promoteIndirectCall(CB, C.TargetFunction, FuncCount, TotalCount,639SamplePGO, &ORE);640assert(TotalCount >= FuncCount);641TotalCount -= FuncCount;642NumOfPGOICallPromotion++;643NumPromoted++;644645if (!EnableVTableProfileUse || C.VTableGUIDAndCounts.empty())646continue;647648// After a virtual call candidate gets promoted, update the vtable's counts649// proportionally. Each vtable-guid in `C.VTableGUIDAndCounts` represents650// a vtable from which the virtual call is loaded. Compute the sum and use651// 128-bit APInt to improve accuracy.652uint64_t SumVTableCount = 0;653for (const auto &[GUID, VTableCount] : C.VTableGUIDAndCounts)654SumVTableCount += VTableCount;655656for (const auto &[GUID, VTableCount] : C.VTableGUIDAndCounts) {657APInt APFuncCount((unsigned)128, FuncCount, false /*signed*/);658APFuncCount *= VTableCount;659VTableGUIDCounts[GUID] -= APFuncCount.udiv(SumVTableCount).getZExtValue();660}661}662if (NumPromoted == 0)663return false;664665assert(NumPromoted <= ICallProfDataRef.size() &&666"Number of promoted functions should not be greater than the number "667"of values in profile metadata");668669// Update value profiles on the indirect call.670updateFuncValueProfiles(CB, ICallProfDataRef.slice(NumPromoted), TotalCount,671NumCandidates);672updateVPtrValueProfiles(VPtr, VTableGUIDCounts);673return true;674}675676void IndirectCallPromoter::updateFuncValueProfiles(677CallBase &CB, ArrayRef<InstrProfValueData> CallVDs, uint64_t TotalCount,678uint32_t MaxMDCount) {679// First clear the existing !prof.680CB.setMetadata(LLVMContext::MD_prof, nullptr);681// Annotate the remaining value profiles if counter is not zero.682if (TotalCount != 0)683annotateValueSite(M, CB, CallVDs, TotalCount, IPVK_IndirectCallTarget,684MaxMDCount);685}686687void IndirectCallPromoter::updateVPtrValueProfiles(688Instruction *VPtr, VTableGUIDCountsMap &VTableGUIDCounts) {689if (!EnableVTableProfileUse || VPtr == nullptr ||690!VPtr->getMetadata(LLVMContext::MD_prof))691return;692VPtr->setMetadata(LLVMContext::MD_prof, nullptr);693std::vector<InstrProfValueData> VTableValueProfiles;694uint64_t TotalVTableCount = 0;695for (auto [GUID, Count] : VTableGUIDCounts) {696if (Count == 0)697continue;698699VTableValueProfiles.push_back({GUID, Count});700TotalVTableCount += Count;701}702llvm::sort(VTableValueProfiles,703[](const InstrProfValueData &LHS, const InstrProfValueData &RHS) {704return LHS.Count > RHS.Count;705});706707annotateValueSite(M, *VPtr, VTableValueProfiles, TotalVTableCount,708IPVK_VTableTarget, VTableValueProfiles.size());709}710711bool IndirectCallPromoter::tryToPromoteWithVTableCmp(712CallBase &CB, Instruction *VPtr, ArrayRef<PromotionCandidate> Candidates,713uint64_t TotalFuncCount, uint32_t NumCandidates,714MutableArrayRef<InstrProfValueData> ICallProfDataRef,715VTableGUIDCountsMap &VTableGUIDCounts) {716SmallVector<uint64_t, 4> PromotedFuncCount;717718for (const auto &Candidate : Candidates) {719for (auto &[GUID, Count] : Candidate.VTableGUIDAndCounts)720VTableGUIDCounts[GUID] -= Count;721722// 'OriginalBB' is the basic block of indirect call. After each candidate723// is promoted, a new basic block is created for the indirect fallback basic724// block and indirect call `CB` is moved into this new BB.725BasicBlock *OriginalBB = CB.getParent();726promoteCallWithVTableCmp(727CB, VPtr, Candidate.TargetFunction, Candidate.AddressPoints,728createBranchWeights(CB.getContext(), Candidate.Count,729TotalFuncCount - Candidate.Count));730731int SinkCount = tryToSinkInstructions(OriginalBB, CB.getParent());732733ORE.emit([&]() {734OptimizationRemark Remark(DEBUG_TYPE, "Promoted", &CB);735736const auto &VTableGUIDAndCounts = Candidate.VTableGUIDAndCounts;737Remark << "Promote indirect call to "738<< ore::NV("DirectCallee", Candidate.TargetFunction)739<< " with count " << ore::NV("Count", Candidate.Count)740<< " out of " << ore::NV("TotalCount", TotalFuncCount) << ", sink "741<< ore::NV("SinkCount", SinkCount)742<< " instruction(s) and compare "743<< ore::NV("VTable", VTableGUIDAndCounts.size())744<< " vtable(s): {";745746// Sort GUIDs so remark message is deterministic.747std::set<uint64_t> GUIDSet;748for (auto [GUID, Count] : VTableGUIDAndCounts)749GUIDSet.insert(GUID);750for (auto Iter = GUIDSet.begin(); Iter != GUIDSet.end(); Iter++) {751if (Iter != GUIDSet.begin())752Remark << ", ";753Remark << ore::NV("VTable", Symtab->getGlobalVariable(*Iter));754}755756Remark << "}";757758return Remark;759});760761PromotedFuncCount.push_back(Candidate.Count);762763assert(TotalFuncCount >= Candidate.Count &&764"Within one prof metadata, total count is the sum of counts from "765"individual <target, count> pairs");766// Use std::min since 'TotalFuncCount' is the saturated sum of individual767// counts, see768// https://github.com/llvm/llvm-project/blob/abedb3b8356d5d56f1c575c4f7682fba2cb19787/llvm/lib/ProfileData/InstrProf.cpp#L1281-L1288769TotalFuncCount -= std::min(TotalFuncCount, Candidate.Count);770NumOfPGOICallPromotion++;771}772773if (PromotedFuncCount.empty())774return false;775776// Update value profiles for 'CB' and 'VPtr', assuming that each 'CB' has a777// a distinct 'VPtr'.778// FIXME: When Clang `-fstrict-vtable-pointers` is enabled, a vtable might be779// used to load multiple virtual functions. The vtable profiles needs to be780// updated properly in that case (e.g, for each indirect call annotate both781// type profiles and function profiles in one !prof).782for (size_t I = 0; I < PromotedFuncCount.size(); I++)783ICallProfDataRef[I].Count -=784std::max(PromotedFuncCount[I], ICallProfDataRef[I].Count);785// Sort value profiles by count in descending order.786llvm::stable_sort(ICallProfDataRef, [](const InstrProfValueData &LHS,787const InstrProfValueData &RHS) {788return LHS.Count > RHS.Count;789});790// Drop the <target-value, count> pair if count is zero.791ArrayRef<InstrProfValueData> VDs(792ICallProfDataRef.begin(),793llvm::upper_bound(ICallProfDataRef, 0U,794[](uint64_t Count, const InstrProfValueData &ProfData) {795return ProfData.Count <= Count;796}));797updateFuncValueProfiles(CB, VDs, TotalFuncCount, NumCandidates);798updateVPtrValueProfiles(VPtr, VTableGUIDCounts);799return true;800}801802// Traverse all the indirect-call callsite and get the value profile803// annotation to perform indirect-call promotion.804bool IndirectCallPromoter::processFunction(ProfileSummaryInfo *PSI) {805bool Changed = false;806ICallPromotionAnalysis ICallAnalysis;807for (auto *CB : findIndirectCalls(F)) {808uint32_t NumCandidates;809uint64_t TotalCount;810auto ICallProfDataRef = ICallAnalysis.getPromotionCandidatesForInstruction(811CB, TotalCount, NumCandidates);812if (!NumCandidates ||813(PSI && PSI->hasProfileSummary() && !PSI->isHotCount(TotalCount)))814continue;815816auto PromotionCandidates = getPromotionCandidatesForCallSite(817*CB, ICallProfDataRef, TotalCount, NumCandidates);818819VTableGUIDCountsMap VTableGUIDCounts;820Instruction *VPtr =821computeVTableInfos(CB, VTableGUIDCounts, PromotionCandidates);822823if (isProfitableToCompareVTables(*CB, PromotionCandidates, TotalCount))824Changed |= tryToPromoteWithVTableCmp(*CB, VPtr, PromotionCandidates,825TotalCount, NumCandidates,826ICallProfDataRef, VTableGUIDCounts);827else828Changed |= tryToPromoteWithFuncCmp(*CB, VPtr, PromotionCandidates,829TotalCount, ICallProfDataRef,830NumCandidates, VTableGUIDCounts);831}832return Changed;833}834835// TODO: Return false if the function addressing and vtable load instructions836// cannot sink to indirect fallback.837bool IndirectCallPromoter::isProfitableToCompareVTables(838const CallBase &CB, ArrayRef<PromotionCandidate> Candidates,839uint64_t TotalCount) {840if (!EnableVTableProfileUse || Candidates.empty())841return false;842LLVM_DEBUG(dbgs() << "\nEvaluating vtable profitability for callsite #"843<< NumOfPGOICallsites << CB << "\n");844uint64_t RemainingVTableCount = TotalCount;845const size_t CandidateSize = Candidates.size();846for (size_t I = 0; I < CandidateSize; I++) {847auto &Candidate = Candidates[I];848auto &VTableGUIDAndCounts = Candidate.VTableGUIDAndCounts;849850LLVM_DEBUG(dbgs() << " Candidate " << I << " FunctionCount: "851<< Candidate.Count << ", VTableCounts:");852// Add [[maybe_unused]] since <GUID, Count> are only used by LLVM_DEBUG.853for ([[maybe_unused]] auto &[GUID, Count] : VTableGUIDAndCounts)854LLVM_DEBUG(dbgs() << " {" << Symtab->getGlobalVariable(GUID)->getName()855<< ", " << Count << "}");856LLVM_DEBUG(dbgs() << "\n");857858uint64_t CandidateVTableCount = 0;859for (auto &[GUID, Count] : VTableGUIDAndCounts)860CandidateVTableCount += Count;861862if (CandidateVTableCount < Candidate.Count * ICPVTablePercentageThreshold) {863LLVM_DEBUG(864dbgs() << " function count " << Candidate.Count865<< " and its vtable sum count " << CandidateVTableCount866<< " have discrepancies. Bail out vtable comparison.\n");867return false;868}869870RemainingVTableCount -= Candidate.Count;871872// 'MaxNumVTable' limits the number of vtables to make vtable comparison873// profitable. Comparing multiple vtables for one function candidate will874// insert additional instructions on the hot path, and allowing more than875// one vtable for non last candidates may or may not elongate the dependency876// chain for the subsequent candidates. Set its value to 1 for non-last877// candidate and allow option to override it for the last candidate.878int MaxNumVTable = 1;879if (I == CandidateSize - 1)880MaxNumVTable = ICPMaxNumVTableLastCandidate;881882if ((int)Candidate.AddressPoints.size() > MaxNumVTable) {883LLVM_DEBUG(dbgs() << " allow at most " << MaxNumVTable << " and got "884<< Candidate.AddressPoints.size()885<< " vtables. Bail out for vtable comparison.\n");886return false;887}888}889890// If the indirect fallback is not cold, don't compare vtables.891if (PSI && PSI->hasProfileSummary() &&892!PSI->isColdCount(RemainingVTableCount)) {893LLVM_DEBUG(dbgs() << " Indirect fallback basic block is not cold. Bail "894"out for vtable comparison.\n");895return false;896}897898return true;899}900901// For virtual calls in the module, collect per-callsite information which will902// be used to associate an ICP candidate with a vtable and a specific function903// in the vtable. With type intrinsics (llvm.type.test), we can find virtual904// calls in a compile-time efficient manner (by iterating its users) and more905// importantly use the compatible type later to figure out the function byte906// offset relative to the start of vtables.907static void908computeVirtualCallSiteTypeInfoMap(Module &M, ModuleAnalysisManager &MAM,909VirtualCallSiteTypeInfoMap &VirtualCSInfo) {910// Right now only llvm.type.test is used to find out virtual call sites.911// With ThinLTO and whole-program-devirtualization, llvm.type.test and912// llvm.public.type.test are emitted, and llvm.public.type.test is either913// refined to llvm.type.test or dropped before indirect-call-promotion pass.914//915// FIXME: For fullLTO with VFE, `llvm.type.checked.load intrinsic` is emitted.916// Find out virtual calls by looking at users of llvm.type.checked.load in917// that case.918Function *TypeTestFunc =919M.getFunction(Intrinsic::getName(Intrinsic::type_test));920if (!TypeTestFunc || TypeTestFunc->use_empty())921return;922923auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();924auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & {925return FAM.getResult<DominatorTreeAnalysis>(F);926};927// Iterate all type.test calls to find all indirect calls.928for (Use &U : llvm::make_early_inc_range(TypeTestFunc->uses())) {929auto *CI = dyn_cast<CallInst>(U.getUser());930if (!CI)931continue;932auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1));933if (!TypeMDVal)934continue;935auto *CompatibleTypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());936if (!CompatibleTypeId)937continue;938939// Find out all devirtualizable call sites given a llvm.type.test940// intrinsic call.941SmallVector<DevirtCallSite, 1> DevirtCalls;942SmallVector<CallInst *, 1> Assumes;943auto &DT = LookupDomTree(*CI->getFunction());944findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);945946for (auto &DevirtCall : DevirtCalls) {947CallBase &CB = DevirtCall.CB;948// Given an indirect call, try find the instruction which loads a949// pointer to virtual table.950Instruction *VTablePtr =951PGOIndirectCallVisitor::tryGetVTableInstruction(&CB);952if (!VTablePtr)953continue;954VirtualCSInfo[&CB] = {DevirtCall.Offset, VTablePtr,955CompatibleTypeId->getString()};956}957}958}959960// A wrapper function that does the actual work.961static bool promoteIndirectCalls(Module &M, ProfileSummaryInfo *PSI, bool InLTO,962bool SamplePGO, ModuleAnalysisManager &MAM) {963if (DisableICP)964return false;965InstrProfSymtab Symtab;966if (Error E = Symtab.create(M, InLTO)) {967std::string SymtabFailure = toString(std::move(E));968M.getContext().emitError("Failed to create symtab: " + SymtabFailure);969return false;970}971bool Changed = false;972VirtualCallSiteTypeInfoMap VirtualCSInfo;973974if (EnableVTableProfileUse)975computeVirtualCallSiteTypeInfoMap(M, MAM, VirtualCSInfo);976977// VTableAddressPointOffsetVal stores the vtable address points. The vtable978// address point of a given <vtable, address point offset> is static (doesn't979// change after being computed once).980// IndirectCallPromoter::getOrCreateVTableAddressPointVar creates the map981// entry the first time a <vtable, offset> pair is seen, as982// promoteIndirectCalls processes an IR module and calls IndirectCallPromoter983// repeatedly on each function.984VTableAddressPointOffsetValMap VTableAddressPointOffsetVal;985986for (auto &F : M) {987if (F.isDeclaration() || F.hasOptNone())988continue;989990auto &FAM =991MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();992auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);993994IndirectCallPromoter CallPromoter(F, M, PSI, &Symtab, SamplePGO,995VirtualCSInfo,996VTableAddressPointOffsetVal, ORE);997bool FuncChanged = CallPromoter.processFunction(PSI);998if (ICPDUMPAFTER && FuncChanged) {999LLVM_DEBUG(dbgs() << "\n== IR Dump After =="; F.print(dbgs()));1000LLVM_DEBUG(dbgs() << "\n");1001}1002Changed |= FuncChanged;1003if (ICPCutOff != 0 && NumOfPGOICallPromotion >= ICPCutOff) {1004LLVM_DEBUG(dbgs() << " Stop: Cutoff reached.\n");1005break;1006}1007}1008return Changed;1009}10101011PreservedAnalyses PGOIndirectCallPromotion::run(Module &M,1012ModuleAnalysisManager &MAM) {1013ProfileSummaryInfo *PSI = &MAM.getResult<ProfileSummaryAnalysis>(M);10141015if (!promoteIndirectCalls(M, PSI, InLTO | ICPLTOMode,1016SamplePGO | ICPSamplePGOMode, MAM))1017return PreservedAnalyses::all();10181019return PreservedAnalyses::none();1020}102110221023