Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp
35266 views
//===- FunctionSpecialization.cpp - Function Specialization ---------------===//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//===----------------------------------------------------------------------===//78#include "llvm/Transforms/IPO/FunctionSpecialization.h"9#include "llvm/ADT/Statistic.h"10#include "llvm/Analysis/CodeMetrics.h"11#include "llvm/Analysis/ConstantFolding.h"12#include "llvm/Analysis/InlineCost.h"13#include "llvm/Analysis/InstructionSimplify.h"14#include "llvm/Analysis/TargetTransformInfo.h"15#include "llvm/Analysis/ValueLattice.h"16#include "llvm/Analysis/ValueLatticeUtils.h"17#include "llvm/Analysis/ValueTracking.h"18#include "llvm/IR/IntrinsicInst.h"19#include "llvm/Transforms/Scalar/SCCP.h"20#include "llvm/Transforms/Utils/Cloning.h"21#include "llvm/Transforms/Utils/SCCPSolver.h"22#include "llvm/Transforms/Utils/SizeOpts.h"23#include <cmath>2425using namespace llvm;2627#define DEBUG_TYPE "function-specialization"2829STATISTIC(NumSpecsCreated, "Number of specializations created");3031static cl::opt<bool> ForceSpecialization(32"force-specialization", cl::init(false), cl::Hidden, cl::desc(33"Force function specialization for every call site with a constant "34"argument"));3536static cl::opt<unsigned> MaxClones(37"funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc(38"The maximum number of clones allowed for a single function "39"specialization"));4041static cl::opt<unsigned>42MaxDiscoveryIterations("funcspec-max-discovery-iterations", cl::init(100),43cl::Hidden,44cl::desc("The maximum number of iterations allowed "45"when searching for transitive "46"phis"));4748static cl::opt<unsigned> MaxIncomingPhiValues(49"funcspec-max-incoming-phi-values", cl::init(8), cl::Hidden,50cl::desc("The maximum number of incoming values a PHI node can have to be "51"considered during the specialization bonus estimation"));5253static cl::opt<unsigned> MaxBlockPredecessors(54"funcspec-max-block-predecessors", cl::init(2), cl::Hidden, cl::desc(55"The maximum number of predecessors a basic block can have to be "56"considered during the estimation of dead code"));5758static cl::opt<unsigned> MinFunctionSize(59"funcspec-min-function-size", cl::init(300), cl::Hidden, cl::desc(60"Don't specialize functions that have less than this number of "61"instructions"));6263static cl::opt<unsigned> MaxCodeSizeGrowth(64"funcspec-max-codesize-growth", cl::init(3), cl::Hidden, cl::desc(65"Maximum codesize growth allowed per function"));6667static cl::opt<unsigned> MinCodeSizeSavings(68"funcspec-min-codesize-savings", cl::init(20), cl::Hidden, cl::desc(69"Reject specializations whose codesize savings are less than this"70"much percent of the original function size"));7172static cl::opt<unsigned> MinLatencySavings(73"funcspec-min-latency-savings", cl::init(40), cl::Hidden,74cl::desc("Reject specializations whose latency savings are less than this"75"much percent of the original function size"));7677static cl::opt<unsigned> MinInliningBonus(78"funcspec-min-inlining-bonus", cl::init(300), cl::Hidden, cl::desc(79"Reject specializations whose inlining bonus is less than this"80"much percent of the original function size"));8182static cl::opt<bool> SpecializeOnAddress(83"funcspec-on-address", cl::init(false), cl::Hidden, cl::desc(84"Enable function specialization on the address of global values"));8586// Disabled by default as it can significantly increase compilation times.87//88// https://llvm-compile-time-tracker.com89// https://github.com/nikic/llvm-compile-time-tracker90static cl::opt<bool> SpecializeLiteralConstant(91"funcspec-for-literal-constant", cl::init(false), cl::Hidden, cl::desc(92"Enable specialization of functions that take a literal constant as an "93"argument"));9495bool InstCostVisitor::canEliminateSuccessor(BasicBlock *BB, BasicBlock *Succ,96DenseSet<BasicBlock *> &DeadBlocks) {97unsigned I = 0;98return all_of(predecessors(Succ),99[&I, BB, Succ, &DeadBlocks] (BasicBlock *Pred) {100return I++ < MaxBlockPredecessors &&101(Pred == BB || Pred == Succ || DeadBlocks.contains(Pred));102});103}104105// Estimates the codesize savings due to dead code after constant propagation.106// \p WorkList represents the basic blocks of a specialization which will107// eventually become dead once we replace instructions that are known to be108// constants. The successors of such blocks are added to the list as long as109// the \p Solver found they were executable prior to specialization, and only110// if all their predecessors are dead.111Cost InstCostVisitor::estimateBasicBlocks(112SmallVectorImpl<BasicBlock *> &WorkList) {113Cost CodeSize = 0;114// Accumulate the instruction cost of each basic block weighted by frequency.115while (!WorkList.empty()) {116BasicBlock *BB = WorkList.pop_back_val();117118// These blocks are considered dead as far as the InstCostVisitor119// is concerned. They haven't been proven dead yet by the Solver,120// but may become if we propagate the specialization arguments.121if (!DeadBlocks.insert(BB).second)122continue;123124for (Instruction &I : *BB) {125// Disregard SSA copies.126if (auto *II = dyn_cast<IntrinsicInst>(&I))127if (II->getIntrinsicID() == Intrinsic::ssa_copy)128continue;129// If it's a known constant we have already accounted for it.130if (KnownConstants.contains(&I))131continue;132133Cost C = TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);134135LLVM_DEBUG(dbgs() << "FnSpecialization: CodeSize " << C136<< " for user " << I << "\n");137CodeSize += C;138}139140// Keep adding dead successors to the list as long as they are141// executable and only reachable from dead blocks.142for (BasicBlock *SuccBB : successors(BB))143if (isBlockExecutable(SuccBB) &&144canEliminateSuccessor(BB, SuccBB, DeadBlocks))145WorkList.push_back(SuccBB);146}147return CodeSize;148}149150static Constant *findConstantFor(Value *V, ConstMap &KnownConstants) {151if (auto *C = dyn_cast<Constant>(V))152return C;153return KnownConstants.lookup(V);154}155156Bonus InstCostVisitor::getBonusFromPendingPHIs() {157Bonus B;158while (!PendingPHIs.empty()) {159Instruction *Phi = PendingPHIs.pop_back_val();160// The pending PHIs could have been proven dead by now.161if (isBlockExecutable(Phi->getParent()))162B += getUserBonus(Phi);163}164return B;165}166167/// Compute a bonus for replacing argument \p A with constant \p C.168Bonus InstCostVisitor::getSpecializationBonus(Argument *A, Constant *C) {169LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: "170<< C->getNameOrAsOperand() << "\n");171Bonus B;172for (auto *U : A->users())173if (auto *UI = dyn_cast<Instruction>(U))174if (isBlockExecutable(UI->getParent()))175B += getUserBonus(UI, A, C);176177LLVM_DEBUG(dbgs() << "FnSpecialization: Accumulated bonus {CodeSize = "178<< B.CodeSize << ", Latency = " << B.Latency179<< "} for argument " << *A << "\n");180return B;181}182183Bonus InstCostVisitor::getUserBonus(Instruction *User, Value *Use, Constant *C) {184// We have already propagated a constant for this user.185if (KnownConstants.contains(User))186return {0, 0};187188// Cache the iterator before visiting.189LastVisited = Use ? KnownConstants.insert({Use, C}).first190: KnownConstants.end();191192Cost CodeSize = 0;193if (auto *I = dyn_cast<SwitchInst>(User)) {194CodeSize = estimateSwitchInst(*I);195} else if (auto *I = dyn_cast<BranchInst>(User)) {196CodeSize = estimateBranchInst(*I);197} else {198C = visit(*User);199if (!C)200return {0, 0};201}202203// Even though it doesn't make sense to bind switch and branch instructions204// with a constant, unlike any other instruction type, it prevents estimating205// their bonus multiple times.206KnownConstants.insert({User, C});207208CodeSize += TTI.getInstructionCost(User, TargetTransformInfo::TCK_CodeSize);209210uint64_t Weight = BFI.getBlockFreq(User->getParent()).getFrequency() /211BFI.getEntryFreq().getFrequency();212213Cost Latency = Weight *214TTI.getInstructionCost(User, TargetTransformInfo::TCK_Latency);215216LLVM_DEBUG(dbgs() << "FnSpecialization: {CodeSize = " << CodeSize217<< ", Latency = " << Latency << "} for user "218<< *User << "\n");219220Bonus B(CodeSize, Latency);221for (auto *U : User->users())222if (auto *UI = dyn_cast<Instruction>(U))223if (UI != User && isBlockExecutable(UI->getParent()))224B += getUserBonus(UI, User, C);225226return B;227}228229Cost InstCostVisitor::estimateSwitchInst(SwitchInst &I) {230assert(LastVisited != KnownConstants.end() && "Invalid iterator!");231232if (I.getCondition() != LastVisited->first)233return 0;234235auto *C = dyn_cast<ConstantInt>(LastVisited->second);236if (!C)237return 0;238239BasicBlock *Succ = I.findCaseValue(C)->getCaseSuccessor();240// Initialize the worklist with the dead basic blocks. These are the241// destination labels which are different from the one corresponding242// to \p C. They should be executable and have a unique predecessor.243SmallVector<BasicBlock *> WorkList;244for (const auto &Case : I.cases()) {245BasicBlock *BB = Case.getCaseSuccessor();246if (BB != Succ && isBlockExecutable(BB) &&247canEliminateSuccessor(I.getParent(), BB, DeadBlocks))248WorkList.push_back(BB);249}250251return estimateBasicBlocks(WorkList);252}253254Cost InstCostVisitor::estimateBranchInst(BranchInst &I) {255assert(LastVisited != KnownConstants.end() && "Invalid iterator!");256257if (I.getCondition() != LastVisited->first)258return 0;259260BasicBlock *Succ = I.getSuccessor(LastVisited->second->isOneValue());261// Initialize the worklist with the dead successor as long as262// it is executable and has a unique predecessor.263SmallVector<BasicBlock *> WorkList;264if (isBlockExecutable(Succ) &&265canEliminateSuccessor(I.getParent(), Succ, DeadBlocks))266WorkList.push_back(Succ);267268return estimateBasicBlocks(WorkList);269}270271bool InstCostVisitor::discoverTransitivelyIncomingValues(272Constant *Const, PHINode *Root, DenseSet<PHINode *> &TransitivePHIs) {273274SmallVector<PHINode *, 64> WorkList;275WorkList.push_back(Root);276unsigned Iter = 0;277278while (!WorkList.empty()) {279PHINode *PN = WorkList.pop_back_val();280281if (++Iter > MaxDiscoveryIterations ||282PN->getNumIncomingValues() > MaxIncomingPhiValues)283return false;284285if (!TransitivePHIs.insert(PN).second)286continue;287288for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {289Value *V = PN->getIncomingValue(I);290291// Disregard self-references and dead incoming values.292if (auto *Inst = dyn_cast<Instruction>(V))293if (Inst == PN || DeadBlocks.contains(PN->getIncomingBlock(I)))294continue;295296if (Constant *C = findConstantFor(V, KnownConstants)) {297// Not all incoming values are the same constant. Bail immediately.298if (C != Const)299return false;300continue;301}302303if (auto *Phi = dyn_cast<PHINode>(V)) {304WorkList.push_back(Phi);305continue;306}307308// We can't reason about anything else.309return false;310}311}312return true;313}314315Constant *InstCostVisitor::visitPHINode(PHINode &I) {316if (I.getNumIncomingValues() > MaxIncomingPhiValues)317return nullptr;318319bool Inserted = VisitedPHIs.insert(&I).second;320Constant *Const = nullptr;321bool HaveSeenIncomingPHI = false;322323for (unsigned Idx = 0, E = I.getNumIncomingValues(); Idx != E; ++Idx) {324Value *V = I.getIncomingValue(Idx);325326// Disregard self-references and dead incoming values.327if (auto *Inst = dyn_cast<Instruction>(V))328if (Inst == &I || DeadBlocks.contains(I.getIncomingBlock(Idx)))329continue;330331if (Constant *C = findConstantFor(V, KnownConstants)) {332if (!Const)333Const = C;334// Not all incoming values are the same constant. Bail immediately.335if (C != Const)336return nullptr;337continue;338}339340if (Inserted) {341// First time we are seeing this phi. We will retry later, after342// all the constant arguments have been propagated. Bail for now.343PendingPHIs.push_back(&I);344return nullptr;345}346347if (isa<PHINode>(V)) {348// Perhaps it is a Transitive Phi. We will confirm later.349HaveSeenIncomingPHI = true;350continue;351}352353// We can't reason about anything else.354return nullptr;355}356357if (!Const)358return nullptr;359360if (!HaveSeenIncomingPHI)361return Const;362363DenseSet<PHINode *> TransitivePHIs;364if (!discoverTransitivelyIncomingValues(Const, &I, TransitivePHIs))365return nullptr;366367return Const;368}369370Constant *InstCostVisitor::visitFreezeInst(FreezeInst &I) {371assert(LastVisited != KnownConstants.end() && "Invalid iterator!");372373if (isGuaranteedNotToBeUndefOrPoison(LastVisited->second))374return LastVisited->second;375return nullptr;376}377378Constant *InstCostVisitor::visitCallBase(CallBase &I) {379Function *F = I.getCalledFunction();380if (!F || !canConstantFoldCallTo(&I, F))381return nullptr;382383SmallVector<Constant *, 8> Operands;384Operands.reserve(I.getNumOperands());385386for (unsigned Idx = 0, E = I.getNumOperands() - 1; Idx != E; ++Idx) {387Value *V = I.getOperand(Idx);388Constant *C = findConstantFor(V, KnownConstants);389if (!C)390return nullptr;391Operands.push_back(C);392}393394auto Ops = ArrayRef(Operands.begin(), Operands.end());395return ConstantFoldCall(&I, F, Ops);396}397398Constant *InstCostVisitor::visitLoadInst(LoadInst &I) {399assert(LastVisited != KnownConstants.end() && "Invalid iterator!");400401if (isa<ConstantPointerNull>(LastVisited->second))402return nullptr;403return ConstantFoldLoadFromConstPtr(LastVisited->second, I.getType(), DL);404}405406Constant *InstCostVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {407SmallVector<Constant *, 8> Operands;408Operands.reserve(I.getNumOperands());409410for (unsigned Idx = 0, E = I.getNumOperands(); Idx != E; ++Idx) {411Value *V = I.getOperand(Idx);412Constant *C = findConstantFor(V, KnownConstants);413if (!C)414return nullptr;415Operands.push_back(C);416}417418auto Ops = ArrayRef(Operands.begin(), Operands.end());419return ConstantFoldInstOperands(&I, Ops, DL);420}421422Constant *InstCostVisitor::visitSelectInst(SelectInst &I) {423assert(LastVisited != KnownConstants.end() && "Invalid iterator!");424425if (I.getCondition() != LastVisited->first)426return nullptr;427428Value *V = LastVisited->second->isZeroValue() ? I.getFalseValue()429: I.getTrueValue();430Constant *C = findConstantFor(V, KnownConstants);431return C;432}433434Constant *InstCostVisitor::visitCastInst(CastInst &I) {435return ConstantFoldCastOperand(I.getOpcode(), LastVisited->second,436I.getType(), DL);437}438439Constant *InstCostVisitor::visitCmpInst(CmpInst &I) {440assert(LastVisited != KnownConstants.end() && "Invalid iterator!");441442bool Swap = I.getOperand(1) == LastVisited->first;443Value *V = Swap ? I.getOperand(0) : I.getOperand(1);444Constant *Other = findConstantFor(V, KnownConstants);445if (!Other)446return nullptr;447448Constant *Const = LastVisited->second;449return Swap ?450ConstantFoldCompareInstOperands(I.getPredicate(), Other, Const, DL)451: ConstantFoldCompareInstOperands(I.getPredicate(), Const, Other, DL);452}453454Constant *InstCostVisitor::visitUnaryOperator(UnaryOperator &I) {455assert(LastVisited != KnownConstants.end() && "Invalid iterator!");456457return ConstantFoldUnaryOpOperand(I.getOpcode(), LastVisited->second, DL);458}459460Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) {461assert(LastVisited != KnownConstants.end() && "Invalid iterator!");462463bool Swap = I.getOperand(1) == LastVisited->first;464Value *V = Swap ? I.getOperand(0) : I.getOperand(1);465Constant *Other = findConstantFor(V, KnownConstants);466if (!Other)467return nullptr;468469Constant *Const = LastVisited->second;470return dyn_cast_or_null<Constant>(Swap ?471simplifyBinOp(I.getOpcode(), Other, Const, SimplifyQuery(DL))472: simplifyBinOp(I.getOpcode(), Const, Other, SimplifyQuery(DL)));473}474475Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca,476CallInst *Call) {477Value *StoreValue = nullptr;478for (auto *User : Alloca->users()) {479// We can't use llvm::isAllocaPromotable() as that would fail because of480// the usage in the CallInst, which is what we check here.481if (User == Call)482continue;483if (auto *Bitcast = dyn_cast<BitCastInst>(User)) {484if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call)485return nullptr;486continue;487}488489if (auto *Store = dyn_cast<StoreInst>(User)) {490// This is a duplicate store, bail out.491if (StoreValue || Store->isVolatile())492return nullptr;493StoreValue = Store->getValueOperand();494continue;495}496// Bail if there is any other unknown usage.497return nullptr;498}499500if (!StoreValue)501return nullptr;502503return getCandidateConstant(StoreValue);504}505506// A constant stack value is an AllocaInst that has a single constant507// value stored to it. Return this constant if such an alloca stack value508// is a function argument.509Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call,510Value *Val) {511if (!Val)512return nullptr;513Val = Val->stripPointerCasts();514if (auto *ConstVal = dyn_cast<ConstantInt>(Val))515return ConstVal;516auto *Alloca = dyn_cast<AllocaInst>(Val);517if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())518return nullptr;519return getPromotableAlloca(Alloca, Call);520}521522// To support specializing recursive functions, it is important to propagate523// constant arguments because after a first iteration of specialisation, a524// reduced example may look like this:525//526// define internal void @RecursiveFn(i32* arg1) {527// %temp = alloca i32, align 4528// store i32 2 i32* %temp, align 4529// call void @RecursiveFn.1(i32* nonnull %temp)530// ret void531// }532//533// Before a next iteration, we need to propagate the constant like so534// which allows further specialization in next iterations.535//536// @funcspec.arg = internal constant i32 2537//538// define internal void @someFunc(i32* arg1) {539// call void @otherFunc(i32* nonnull @funcspec.arg)540// ret void541// }542//543// See if there are any new constant values for the callers of \p F via544// stack variables and promote them to global variables.545void FunctionSpecializer::promoteConstantStackValues(Function *F) {546for (User *U : F->users()) {547548auto *Call = dyn_cast<CallInst>(U);549if (!Call)550continue;551552if (!Solver.isBlockExecutable(Call->getParent()))553continue;554555for (const Use &U : Call->args()) {556unsigned Idx = Call->getArgOperandNo(&U);557Value *ArgOp = Call->getArgOperand(Idx);558Type *ArgOpType = ArgOp->getType();559560if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy())561continue;562563auto *ConstVal = getConstantStackValue(Call, ArgOp);564if (!ConstVal)565continue;566567Value *GV = new GlobalVariable(M, ConstVal->getType(), true,568GlobalValue::InternalLinkage, ConstVal,569"specialized.arg." + Twine(++NGlobals));570Call->setArgOperand(Idx, GV);571}572}573}574575// ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics576// interfere with the promoteConstantStackValues() optimization.577static void removeSSACopy(Function &F) {578for (BasicBlock &BB : F) {579for (Instruction &Inst : llvm::make_early_inc_range(BB)) {580auto *II = dyn_cast<IntrinsicInst>(&Inst);581if (!II)582continue;583if (II->getIntrinsicID() != Intrinsic::ssa_copy)584continue;585Inst.replaceAllUsesWith(II->getOperand(0));586Inst.eraseFromParent();587}588}589}590591/// Remove any ssa_copy intrinsics that may have been introduced.592void FunctionSpecializer::cleanUpSSA() {593for (Function *F : Specializations)594removeSSACopy(*F);595}596597598template <> struct llvm::DenseMapInfo<SpecSig> {599static inline SpecSig getEmptyKey() { return {~0U, {}}; }600601static inline SpecSig getTombstoneKey() { return {~1U, {}}; }602603static unsigned getHashValue(const SpecSig &S) {604return static_cast<unsigned>(hash_value(S));605}606607static bool isEqual(const SpecSig &LHS, const SpecSig &RHS) {608return LHS == RHS;609}610};611612FunctionSpecializer::~FunctionSpecializer() {613LLVM_DEBUG(614if (NumSpecsCreated > 0)615dbgs() << "FnSpecialization: Created " << NumSpecsCreated616<< " specializations in module " << M.getName() << "\n");617// Eliminate dead code.618removeDeadFunctions();619cleanUpSSA();620}621622/// Attempt to specialize functions in the module to enable constant623/// propagation across function boundaries.624///625/// \returns true if at least one function is specialized.626bool FunctionSpecializer::run() {627// Find possible specializations for each function.628SpecMap SM;629SmallVector<Spec, 32> AllSpecs;630unsigned NumCandidates = 0;631for (Function &F : M) {632if (!isCandidateFunction(&F))633continue;634635auto [It, Inserted] = FunctionMetrics.try_emplace(&F);636CodeMetrics &Metrics = It->second;637//Analyze the function.638if (Inserted) {639SmallPtrSet<const Value *, 32> EphValues;640CodeMetrics::collectEphemeralValues(&F, &GetAC(F), EphValues);641for (BasicBlock &BB : F)642Metrics.analyzeBasicBlock(&BB, GetTTI(F), EphValues);643}644645// If the code metrics reveal that we shouldn't duplicate the function,646// or if the code size implies that this function is easy to get inlined,647// then we shouldn't specialize it.648if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() ||649(!ForceSpecialization && !F.hasFnAttribute(Attribute::NoInline) &&650Metrics.NumInsts < MinFunctionSize))651continue;652653// TODO: For now only consider recursive functions when running multiple654// times. This should change if specialization on literal constants gets655// enabled.656if (!Inserted && !Metrics.isRecursive && !SpecializeLiteralConstant)657continue;658659int64_t Sz = *Metrics.NumInsts.getValue();660assert(Sz > 0 && "CodeSize should be positive");661// It is safe to down cast from int64_t, NumInsts is always positive.662unsigned FuncSize = static_cast<unsigned>(Sz);663664LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for "665<< F.getName() << " is " << FuncSize << "\n");666667if (Inserted && Metrics.isRecursive)668promoteConstantStackValues(&F);669670if (!findSpecializations(&F, FuncSize, AllSpecs, SM)) {671LLVM_DEBUG(672dbgs() << "FnSpecialization: No possible specializations found for "673<< F.getName() << "\n");674continue;675}676677++NumCandidates;678}679680if (!NumCandidates) {681LLVM_DEBUG(682dbgs()683<< "FnSpecialization: No possible specializations found in module\n");684return false;685}686687// Choose the most profitable specialisations, which fit in the module688// specialization budget, which is derived from maximum number of689// specializations per specialization candidate function.690auto CompareScore = [&AllSpecs](unsigned I, unsigned J) {691if (AllSpecs[I].Score != AllSpecs[J].Score)692return AllSpecs[I].Score > AllSpecs[J].Score;693return I > J;694};695const unsigned NSpecs =696std::min(NumCandidates * MaxClones, unsigned(AllSpecs.size()));697SmallVector<unsigned> BestSpecs(NSpecs + 1);698std::iota(BestSpecs.begin(), BestSpecs.begin() + NSpecs, 0);699if (AllSpecs.size() > NSpecs) {700LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed "701<< "the maximum number of clones threshold.\n"702<< "FnSpecialization: Specializing the "703<< NSpecs704<< " most profitable candidates.\n");705std::make_heap(BestSpecs.begin(), BestSpecs.begin() + NSpecs, CompareScore);706for (unsigned I = NSpecs, N = AllSpecs.size(); I < N; ++I) {707BestSpecs[NSpecs] = I;708std::push_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);709std::pop_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);710}711}712713LLVM_DEBUG(dbgs() << "FnSpecialization: List of specializations \n";714for (unsigned I = 0; I < NSpecs; ++I) {715const Spec &S = AllSpecs[BestSpecs[I]];716dbgs() << "FnSpecialization: Function " << S.F->getName()717<< " , score " << S.Score << "\n";718for (const ArgInfo &Arg : S.Sig.Args)719dbgs() << "FnSpecialization: FormalArg = "720<< Arg.Formal->getNameOrAsOperand()721<< ", ActualArg = " << Arg.Actual->getNameOrAsOperand()722<< "\n";723});724725// Create the chosen specializations.726SmallPtrSet<Function *, 8> OriginalFuncs;727SmallVector<Function *> Clones;728for (unsigned I = 0; I < NSpecs; ++I) {729Spec &S = AllSpecs[BestSpecs[I]];730S.Clone = createSpecialization(S.F, S.Sig);731732// Update the known call sites to call the clone.733for (CallBase *Call : S.CallSites) {734LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call735<< " to call " << S.Clone->getName() << "\n");736Call->setCalledFunction(S.Clone);737}738739Clones.push_back(S.Clone);740OriginalFuncs.insert(S.F);741}742743Solver.solveWhileResolvedUndefsIn(Clones);744745// Update the rest of the call sites - these are the recursive calls, calls746// to discarded specialisations and calls that may match a specialisation747// after the solver runs.748for (Function *F : OriginalFuncs) {749auto [Begin, End] = SM[F];750updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End);751}752753for (Function *F : Clones) {754if (F->getReturnType()->isVoidTy())755continue;756if (F->getReturnType()->isStructTy()) {757auto *STy = cast<StructType>(F->getReturnType());758if (!Solver.isStructLatticeConstant(F, STy))759continue;760} else {761auto It = Solver.getTrackedRetVals().find(F);762assert(It != Solver.getTrackedRetVals().end() &&763"Return value ought to be tracked");764if (SCCPSolver::isOverdefined(It->second))765continue;766}767for (User *U : F->users()) {768if (auto *CS = dyn_cast<CallBase>(U)) {769//The user instruction does not call our function.770if (CS->getCalledFunction() != F)771continue;772Solver.resetLatticeValueFor(CS);773}774}775}776777// Rerun the solver to notify the users of the modified callsites.778Solver.solveWhileResolvedUndefs();779780for (Function *F : OriginalFuncs)781if (FunctionMetrics[F].isRecursive)782promoteConstantStackValues(F);783784return true;785}786787void FunctionSpecializer::removeDeadFunctions() {788for (Function *F : FullySpecialized) {789LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function "790<< F->getName() << "\n");791if (FAM)792FAM->clear(*F, F->getName());793F->eraseFromParent();794}795FullySpecialized.clear();796}797798/// Clone the function \p F and remove the ssa_copy intrinsics added by799/// the SCCPSolver in the cloned version.800static Function *cloneCandidateFunction(Function *F, unsigned NSpecs) {801ValueToValueMapTy Mappings;802Function *Clone = CloneFunction(F, Mappings);803Clone->setName(F->getName() + ".specialized." + Twine(NSpecs));804removeSSACopy(*Clone);805return Clone;806}807808bool FunctionSpecializer::findSpecializations(Function *F, unsigned FuncSize,809SmallVectorImpl<Spec> &AllSpecs,810SpecMap &SM) {811// A mapping from a specialisation signature to the index of the respective812// entry in the all specialisation array. Used to ensure uniqueness of813// specialisations.814DenseMap<SpecSig, unsigned> UniqueSpecs;815816// Get a list of interesting arguments.817SmallVector<Argument *> Args;818for (Argument &Arg : F->args())819if (isArgumentInteresting(&Arg))820Args.push_back(&Arg);821822if (Args.empty())823return false;824825for (User *U : F->users()) {826if (!isa<CallInst>(U) && !isa<InvokeInst>(U))827continue;828auto &CS = *cast<CallBase>(U);829830// The user instruction does not call our function.831if (CS.getCalledFunction() != F)832continue;833834// If the call site has attribute minsize set, that callsite won't be835// specialized.836if (CS.hasFnAttr(Attribute::MinSize))837continue;838839// If the parent of the call site will never be executed, we don't need840// to worry about the passed value.841if (!Solver.isBlockExecutable(CS.getParent()))842continue;843844// Examine arguments and create a specialisation candidate from the845// constant operands of this call site.846SpecSig S;847for (Argument *A : Args) {848Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo()));849if (!C)850continue;851LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument "852<< A->getName() << " : " << C->getNameOrAsOperand()853<< "\n");854S.Args.push_back({A, C});855}856857if (S.Args.empty())858continue;859860// Check if we have encountered the same specialisation already.861if (auto It = UniqueSpecs.find(S); It != UniqueSpecs.end()) {862// Existing specialisation. Add the call to the list to rewrite, unless863// it's a recursive call. A specialisation, generated because of a864// recursive call may end up as not the best specialisation for all865// the cloned instances of this call, which result from specialising866// functions. Hence we don't rewrite the call directly, but match it with867// the best specialisation once all specialisations are known.868if (CS.getFunction() == F)869continue;870const unsigned Index = It->second;871AllSpecs[Index].CallSites.push_back(&CS);872} else {873// Calculate the specialisation gain.874Bonus B;875unsigned Score = 0;876InstCostVisitor Visitor = getInstCostVisitorFor(F);877for (ArgInfo &A : S.Args) {878B += Visitor.getSpecializationBonus(A.Formal, A.Actual);879Score += getInliningBonus(A.Formal, A.Actual);880}881B += Visitor.getBonusFromPendingPHIs();882883884LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization bonus {CodeSize = "885<< B.CodeSize << ", Latency = " << B.Latency886<< ", Inlining = " << Score << "}\n");887888FunctionGrowth[F] += FuncSize - B.CodeSize;889890auto IsProfitable = [](Bonus &B, unsigned Score, unsigned FuncSize,891unsigned FuncGrowth) -> bool {892// No check required.893if (ForceSpecialization)894return true;895// Minimum inlining bonus.896if (Score > MinInliningBonus * FuncSize / 100)897return true;898// Minimum codesize savings.899if (B.CodeSize < MinCodeSizeSavings * FuncSize / 100)900return false;901// Minimum latency savings.902if (B.Latency < MinLatencySavings * FuncSize / 100)903return false;904// Maximum codesize growth.905if (FuncGrowth / FuncSize > MaxCodeSizeGrowth)906return false;907return true;908};909910// Discard unprofitable specialisations.911if (!IsProfitable(B, Score, FuncSize, FunctionGrowth[F]))912continue;913914// Create a new specialisation entry.915Score += std::max(B.CodeSize, B.Latency);916auto &Spec = AllSpecs.emplace_back(F, S, Score);917if (CS.getFunction() != F)918Spec.CallSites.push_back(&CS);919const unsigned Index = AllSpecs.size() - 1;920UniqueSpecs[S] = Index;921if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted)922It->second.second = Index + 1;923}924}925926return !UniqueSpecs.empty();927}928929bool FunctionSpecializer::isCandidateFunction(Function *F) {930if (F->isDeclaration() || F->arg_empty())931return false;932933if (F->hasFnAttribute(Attribute::NoDuplicate))934return false;935936// Do not specialize the cloned function again.937if (Specializations.contains(F))938return false;939940// If we're optimizing the function for size, we shouldn't specialize it.941if (F->hasOptSize() ||942shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))943return false;944945// Exit if the function is not executable. There's no point in specializing946// a dead function.947if (!Solver.isBlockExecutable(&F->getEntryBlock()))948return false;949950// It wastes time to specialize a function which would get inlined finally.951if (F->hasFnAttribute(Attribute::AlwaysInline))952return false;953954LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()955<< "\n");956return true;957}958959Function *FunctionSpecializer::createSpecialization(Function *F,960const SpecSig &S) {961Function *Clone = cloneCandidateFunction(F, Specializations.size() + 1);962963// The original function does not neccessarily have internal linkage, but the964// clone must.965Clone->setLinkage(GlobalValue::InternalLinkage);966967// Initialize the lattice state of the arguments of the function clone,968// marking the argument on which we specialized the function constant969// with the given value.970Solver.setLatticeValueForSpecializationArguments(Clone, S.Args);971Solver.markBlockExecutable(&Clone->front());972Solver.addArgumentTrackedFunction(Clone);973Solver.addTrackedFunction(Clone);974975// Mark all the specialized functions976Specializations.insert(Clone);977++NumSpecsCreated;978979return Clone;980}981982/// Compute the inlining bonus for replacing argument \p A with constant \p C.983/// The below heuristic is only concerned with exposing inlining984/// opportunities via indirect call promotion. If the argument is not a985/// (potentially casted) function pointer, give up.986unsigned FunctionSpecializer::getInliningBonus(Argument *A, Constant *C) {987Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts());988if (!CalledFunction)989return 0;990991// Get TTI for the called function (used for the inline cost).992auto &CalleeTTI = (GetTTI)(*CalledFunction);993994// Look at all the call sites whose called value is the argument.995// Specializing the function on the argument would allow these indirect996// calls to be promoted to direct calls. If the indirect call promotion997// would likely enable the called function to be inlined, specializing is a998// good idea.999int InliningBonus = 0;1000for (User *U : A->users()) {1001if (!isa<CallInst>(U) && !isa<InvokeInst>(U))1002continue;1003auto *CS = cast<CallBase>(U);1004if (CS->getCalledOperand() != A)1005continue;1006if (CS->getFunctionType() != CalledFunction->getFunctionType())1007continue;10081009// Get the cost of inlining the called function at this call site. Note1010// that this is only an estimate. The called function may eventually1011// change in a way that leads to it not being inlined here, even though1012// inlining looks profitable now. For example, one of its called1013// functions may be inlined into it, making the called function too large1014// to be inlined into this call site.1015//1016// We apply a boost for performing indirect call promotion by increasing1017// the default threshold by the threshold for indirect calls.1018auto Params = getInlineParams();1019Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;1020InlineCost IC =1021getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);10221023// We clamp the bonus for this call to be between zero and the default1024// threshold.1025if (IC.isAlways())1026InliningBonus += Params.DefaultThreshold;1027else if (IC.isVariable() && IC.getCostDelta() > 0)1028InliningBonus += IC.getCostDelta();10291030LLVM_DEBUG(dbgs() << "FnSpecialization: Inlining bonus " << InliningBonus1031<< " for user " << *U << "\n");1032}10331034return InliningBonus > 0 ? static_cast<unsigned>(InliningBonus) : 0;1035}10361037/// Determine if it is possible to specialise the function for constant values1038/// of the formal parameter \p A.1039bool FunctionSpecializer::isArgumentInteresting(Argument *A) {1040// No point in specialization if the argument is unused.1041if (A->user_empty())1042return false;10431044Type *Ty = A->getType();1045if (!Ty->isPointerTy() && (!SpecializeLiteralConstant ||1046(!Ty->isIntegerTy() && !Ty->isFloatingPointTy() && !Ty->isStructTy())))1047return false;10481049// SCCP solver does not record an argument that will be constructed on1050// stack.1051if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory())1052return false;10531054// For non-argument-tracked functions every argument is overdefined.1055if (!Solver.isArgumentTrackedFunction(A->getParent()))1056return true;10571058// Check the lattice value and decide if we should attemt to specialize,1059// based on this argument. No point in specialization, if the lattice value1060// is already a constant.1061bool IsOverdefined = Ty->isStructTy()1062? any_of(Solver.getStructLatticeValueFor(A), SCCPSolver::isOverdefined)1063: SCCPSolver::isOverdefined(Solver.getLatticeValueFor(A));10641065LLVM_DEBUG(1066if (IsOverdefined)1067dbgs() << "FnSpecialization: Found interesting parameter "1068<< A->getNameOrAsOperand() << "\n";1069else1070dbgs() << "FnSpecialization: Nothing to do, parameter "1071<< A->getNameOrAsOperand() << " is already constant\n";1072);1073return IsOverdefined;1074}10751076/// Check if the value \p V (an actual argument) is a constant or can only1077/// have a constant value. Return that constant.1078Constant *FunctionSpecializer::getCandidateConstant(Value *V) {1079if (isa<PoisonValue>(V))1080return nullptr;10811082// Select for possible specialisation values that are constants or1083// are deduced to be constants or constant ranges with a single element.1084Constant *C = dyn_cast<Constant>(V);1085if (!C)1086C = Solver.getConstantOrNull(V);10871088// Don't specialize on (anything derived from) the address of a non-constant1089// global variable, unless explicitly enabled.1090if (C && C->getType()->isPointerTy() && !C->isNullValue())1091if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C));1092GV && !(GV->isConstant() || SpecializeOnAddress))1093return nullptr;10941095return C;1096}10971098void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin,1099const Spec *End) {1100// Collect the call sites that need updating.1101SmallVector<CallBase *> ToUpdate;1102for (User *U : F->users())1103if (auto *CS = dyn_cast<CallBase>(U);1104CS && CS->getCalledFunction() == F &&1105Solver.isBlockExecutable(CS->getParent()))1106ToUpdate.push_back(CS);11071108unsigned NCallsLeft = ToUpdate.size();1109for (CallBase *CS : ToUpdate) {1110bool ShouldDecrementCount = CS->getFunction() == F;11111112// Find the best matching specialisation.1113const Spec *BestSpec = nullptr;1114for (const Spec &S : make_range(Begin, End)) {1115if (!S.Clone || (BestSpec && S.Score <= BestSpec->Score))1116continue;11171118if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) {1119unsigned ArgNo = Arg.Formal->getArgNo();1120return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual;1121}))1122continue;11231124BestSpec = &S;1125}11261127if (BestSpec) {1128LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS1129<< " to call " << BestSpec->Clone->getName() << "\n");1130CS->setCalledFunction(BestSpec->Clone);1131ShouldDecrementCount = true;1132}11331134if (ShouldDecrementCount)1135--NCallsLeft;1136}11371138// If the function has been completely specialized, the original function1139// is no longer needed. Mark it unreachable.1140if (NCallsLeft == 0 && Solver.isArgumentTrackedFunction(F)) {1141Solver.markFunctionUnreachable(F);1142FullySpecialized.insert(F);1143}1144}114511461147