xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1fe6060f1SDimitry Andric //===- FunctionSpecialization.cpp - Function Specialization ---------------===//
2fe6060f1SDimitry Andric //
3fe6060f1SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4fe6060f1SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5fe6060f1SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fe6060f1SDimitry Andric //
7fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
8fe6060f1SDimitry Andric 
9bdd1243dSDimitry Andric #include "llvm/Transforms/IPO/FunctionSpecialization.h"
10fe6060f1SDimitry Andric #include "llvm/ADT/Statistic.h"
11fe6060f1SDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
1206c3fb27SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
13fe6060f1SDimitry Andric #include "llvm/Analysis/InlineCost.h"
1406c3fb27SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
15fe6060f1SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
1681ad6265SDimitry Andric #include "llvm/Analysis/ValueLattice.h"
1781ad6265SDimitry Andric #include "llvm/Analysis/ValueLatticeUtils.h"
1806c3fb27SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
1981ad6265SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
20fe6060f1SDimitry Andric #include "llvm/Transforms/Scalar/SCCP.h"
21fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
2281ad6265SDimitry Andric #include "llvm/Transforms/Utils/SCCPSolver.h"
23fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/SizeOpts.h"
24fe6060f1SDimitry Andric #include <cmath>
25fe6060f1SDimitry Andric 
26fe6060f1SDimitry Andric using namespace llvm;
27fe6060f1SDimitry Andric 
28fe6060f1SDimitry Andric #define DEBUG_TYPE "function-specialization"
29fe6060f1SDimitry Andric 
3006c3fb27SDimitry Andric STATISTIC(NumSpecsCreated, "Number of specializations created");
31fe6060f1SDimitry Andric 
3206c3fb27SDimitry Andric static cl::opt<bool> ForceSpecialization(
3306c3fb27SDimitry Andric     "force-specialization", cl::init(false), cl::Hidden, cl::desc(
3406c3fb27SDimitry Andric     "Force function specialization for every call site with a constant "
3506c3fb27SDimitry Andric     "argument"));
36fe6060f1SDimitry Andric 
3706c3fb27SDimitry Andric static cl::opt<unsigned> MaxClones(
3806c3fb27SDimitry Andric     "funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc(
3906c3fb27SDimitry Andric     "The maximum number of clones allowed for a single function "
4006c3fb27SDimitry Andric     "specialization"));
41fe6060f1SDimitry Andric 
425f757f3fSDimitry Andric static cl::opt<unsigned>
435f757f3fSDimitry Andric     MaxDiscoveryIterations("funcspec-max-discovery-iterations", cl::init(100),
445f757f3fSDimitry Andric                            cl::Hidden,
455f757f3fSDimitry Andric                            cl::desc("The maximum number of iterations allowed "
465f757f3fSDimitry Andric                                     "when searching for transitive "
475f757f3fSDimitry Andric                                     "phis"));
485f757f3fSDimitry Andric 
495f757f3fSDimitry Andric static cl::opt<unsigned> MaxIncomingPhiValues(
505f757f3fSDimitry Andric     "funcspec-max-incoming-phi-values", cl::init(8), cl::Hidden,
515f757f3fSDimitry Andric     cl::desc("The maximum number of incoming values a PHI node can have to be "
525f757f3fSDimitry Andric              "considered during the specialization bonus estimation"));
535f757f3fSDimitry Andric 
545f757f3fSDimitry Andric static cl::opt<unsigned> MaxBlockPredecessors(
555f757f3fSDimitry Andric     "funcspec-max-block-predecessors", cl::init(2), cl::Hidden, cl::desc(
565f757f3fSDimitry Andric     "The maximum number of predecessors a basic block can have to be "
575f757f3fSDimitry Andric     "considered during the estimation of dead code"));
585f757f3fSDimitry Andric 
5906c3fb27SDimitry Andric static cl::opt<unsigned> MinFunctionSize(
605f757f3fSDimitry Andric     "funcspec-min-function-size", cl::init(300), cl::Hidden, cl::desc(
6106c3fb27SDimitry Andric     "Don't specialize functions that have less than this number of "
6206c3fb27SDimitry Andric     "instructions"));
63fe6060f1SDimitry Andric 
645f757f3fSDimitry Andric static cl::opt<unsigned> MaxCodeSizeGrowth(
655f757f3fSDimitry Andric     "funcspec-max-codesize-growth", cl::init(3), cl::Hidden, cl::desc(
665f757f3fSDimitry Andric     "Maximum codesize growth allowed per function"));
675f757f3fSDimitry Andric 
685f757f3fSDimitry Andric static cl::opt<unsigned> MinCodeSizeSavings(
695f757f3fSDimitry Andric     "funcspec-min-codesize-savings", cl::init(20), cl::Hidden, cl::desc(
705f757f3fSDimitry Andric     "Reject specializations whose codesize savings are less than this"
715f757f3fSDimitry Andric     "much percent of the original function size"));
725f757f3fSDimitry Andric 
735f757f3fSDimitry Andric static cl::opt<unsigned> MinLatencySavings(
745f757f3fSDimitry Andric     "funcspec-min-latency-savings", cl::init(40), cl::Hidden,
755f757f3fSDimitry Andric     cl::desc("Reject specializations whose latency savings are less than this"
765f757f3fSDimitry Andric              "much percent of the original function size"));
775f757f3fSDimitry Andric 
785f757f3fSDimitry Andric static cl::opt<unsigned> MinInliningBonus(
795f757f3fSDimitry Andric     "funcspec-min-inlining-bonus", cl::init(300), cl::Hidden, cl::desc(
805f757f3fSDimitry Andric     "Reject specializations whose inlining bonus is less than this"
815f757f3fSDimitry Andric     "much percent of the original function size"));
825f757f3fSDimitry Andric 
8306c3fb27SDimitry Andric static cl::opt<bool> SpecializeOnAddress(
8406c3fb27SDimitry Andric     "funcspec-on-address", cl::init(false), cl::Hidden, cl::desc(
8506c3fb27SDimitry Andric     "Enable function specialization on the address of global values"));
86349cc55cSDimitry Andric 
8781ad6265SDimitry Andric // Disabled by default as it can significantly increase compilation times.
8881ad6265SDimitry Andric //
8981ad6265SDimitry Andric // https://llvm-compile-time-tracker.com
9081ad6265SDimitry Andric // https://github.com/nikic/llvm-compile-time-tracker
9106c3fb27SDimitry Andric static cl::opt<bool> SpecializeLiteralConstant(
9206c3fb27SDimitry Andric     "funcspec-for-literal-constant", cl::init(false), cl::Hidden, cl::desc(
9306c3fb27SDimitry Andric     "Enable specialization of functions that take a literal constant as an "
9406c3fb27SDimitry Andric     "argument"));
9506c3fb27SDimitry Andric 
965f757f3fSDimitry Andric bool InstCostVisitor::canEliminateSuccessor(BasicBlock *BB, BasicBlock *Succ,
975f757f3fSDimitry Andric                                          DenseSet<BasicBlock *> &DeadBlocks) {
985f757f3fSDimitry Andric   unsigned I = 0;
995f757f3fSDimitry Andric   return all_of(predecessors(Succ),
1005f757f3fSDimitry Andric     [&I, BB, Succ, &DeadBlocks] (BasicBlock *Pred) {
1015f757f3fSDimitry Andric     return I++ < MaxBlockPredecessors &&
1025f757f3fSDimitry Andric       (Pred == BB || Pred == Succ || DeadBlocks.contains(Pred));
1035f757f3fSDimitry Andric   });
1045f757f3fSDimitry Andric }
10506c3fb27SDimitry Andric 
1065f757f3fSDimitry Andric // Estimates the codesize savings due to dead code after constant propagation.
1075f757f3fSDimitry Andric // \p WorkList represents the basic blocks of a specialization which will
1085f757f3fSDimitry Andric // eventually become dead once we replace instructions that are known to be
1095f757f3fSDimitry Andric // constants. The successors of such blocks are added to the list as long as
1105f757f3fSDimitry Andric // the \p Solver found they were executable prior to specialization, and only
1115f757f3fSDimitry Andric // if all their predecessors are dead.
1125f757f3fSDimitry Andric Cost InstCostVisitor::estimateBasicBlocks(
1135f757f3fSDimitry Andric                           SmallVectorImpl<BasicBlock *> &WorkList) {
1145f757f3fSDimitry Andric   Cost CodeSize = 0;
11506c3fb27SDimitry Andric   // Accumulate the instruction cost of each basic block weighted by frequency.
11606c3fb27SDimitry Andric   while (!WorkList.empty()) {
11706c3fb27SDimitry Andric     BasicBlock *BB = WorkList.pop_back_val();
11806c3fb27SDimitry Andric 
1195f757f3fSDimitry Andric     // These blocks are considered dead as far as the InstCostVisitor
1205f757f3fSDimitry Andric     // is concerned. They haven't been proven dead yet by the Solver,
1215f757f3fSDimitry Andric     // but may become if we propagate the specialization arguments.
1225f757f3fSDimitry Andric     if (!DeadBlocks.insert(BB).second)
12306c3fb27SDimitry Andric       continue;
12406c3fb27SDimitry Andric 
12506c3fb27SDimitry Andric     for (Instruction &I : *BB) {
12606c3fb27SDimitry Andric       // Disregard SSA copies.
12706c3fb27SDimitry Andric       if (auto *II = dyn_cast<IntrinsicInst>(&I))
12806c3fb27SDimitry Andric         if (II->getIntrinsicID() == Intrinsic::ssa_copy)
12906c3fb27SDimitry Andric           continue;
13006c3fb27SDimitry Andric       // If it's a known constant we have already accounted for it.
13106c3fb27SDimitry Andric       if (KnownConstants.contains(&I))
13206c3fb27SDimitry Andric         continue;
13306c3fb27SDimitry Andric 
1345f757f3fSDimitry Andric       Cost C = TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
13506c3fb27SDimitry Andric 
1365f757f3fSDimitry Andric       LLVM_DEBUG(dbgs() << "FnSpecialization:     CodeSize " << C
1375f757f3fSDimitry Andric                         << " for user " << I << "\n");
1385f757f3fSDimitry Andric       CodeSize += C;
13906c3fb27SDimitry Andric     }
14006c3fb27SDimitry Andric 
14106c3fb27SDimitry Andric     // Keep adding dead successors to the list as long as they are
1425f757f3fSDimitry Andric     // executable and only reachable from dead blocks.
14306c3fb27SDimitry Andric     for (BasicBlock *SuccBB : successors(BB))
1445f757f3fSDimitry Andric       if (isBlockExecutable(SuccBB) &&
1455f757f3fSDimitry Andric           canEliminateSuccessor(BB, SuccBB, DeadBlocks))
14606c3fb27SDimitry Andric         WorkList.push_back(SuccBB);
14706c3fb27SDimitry Andric   }
1485f757f3fSDimitry Andric   return CodeSize;
14906c3fb27SDimitry Andric }
15006c3fb27SDimitry Andric 
15106c3fb27SDimitry Andric static Constant *findConstantFor(Value *V, ConstMap &KnownConstants) {
15206c3fb27SDimitry Andric   if (auto *C = dyn_cast<Constant>(V))
15306c3fb27SDimitry Andric     return C;
1545f757f3fSDimitry Andric   return KnownConstants.lookup(V);
15506c3fb27SDimitry Andric }
15606c3fb27SDimitry Andric 
1575f757f3fSDimitry Andric Bonus InstCostVisitor::getBonusFromPendingPHIs() {
1585f757f3fSDimitry Andric   Bonus B;
1595f757f3fSDimitry Andric   while (!PendingPHIs.empty()) {
1605f757f3fSDimitry Andric     Instruction *Phi = PendingPHIs.pop_back_val();
1615f757f3fSDimitry Andric     // The pending PHIs could have been proven dead by now.
1625f757f3fSDimitry Andric     if (isBlockExecutable(Phi->getParent()))
1635f757f3fSDimitry Andric       B += getUserBonus(Phi);
1645f757f3fSDimitry Andric   }
1655f757f3fSDimitry Andric   return B;
1665f757f3fSDimitry Andric }
1675f757f3fSDimitry Andric 
1685f757f3fSDimitry Andric /// Compute a bonus for replacing argument \p A with constant \p C.
1695f757f3fSDimitry Andric Bonus InstCostVisitor::getSpecializationBonus(Argument *A, Constant *C) {
1705f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: "
1715f757f3fSDimitry Andric                     << C->getNameOrAsOperand() << "\n");
1725f757f3fSDimitry Andric   Bonus B;
1735f757f3fSDimitry Andric   for (auto *U : A->users())
1745f757f3fSDimitry Andric     if (auto *UI = dyn_cast<Instruction>(U))
1755f757f3fSDimitry Andric       if (isBlockExecutable(UI->getParent()))
1765f757f3fSDimitry Andric         B += getUserBonus(UI, A, C);
1775f757f3fSDimitry Andric 
1785f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "FnSpecialization:   Accumulated bonus {CodeSize = "
1795f757f3fSDimitry Andric                     << B.CodeSize << ", Latency = " << B.Latency
1805f757f3fSDimitry Andric                     << "} for argument " << *A << "\n");
1815f757f3fSDimitry Andric   return B;
1825f757f3fSDimitry Andric }
1835f757f3fSDimitry Andric 
1845f757f3fSDimitry Andric Bonus InstCostVisitor::getUserBonus(Instruction *User, Value *Use, Constant *C) {
1855f757f3fSDimitry Andric   // We have already propagated a constant for this user.
1865f757f3fSDimitry Andric   if (KnownConstants.contains(User))
1875f757f3fSDimitry Andric     return {0, 0};
1885f757f3fSDimitry Andric 
18906c3fb27SDimitry Andric   // Cache the iterator before visiting.
1905f757f3fSDimitry Andric   LastVisited = Use ? KnownConstants.insert({Use, C}).first
1915f757f3fSDimitry Andric                     : KnownConstants.end();
19206c3fb27SDimitry Andric 
1935f757f3fSDimitry Andric   Cost CodeSize = 0;
1945f757f3fSDimitry Andric   if (auto *I = dyn_cast<SwitchInst>(User)) {
1955f757f3fSDimitry Andric     CodeSize = estimateSwitchInst(*I);
1965f757f3fSDimitry Andric   } else if (auto *I = dyn_cast<BranchInst>(User)) {
1975f757f3fSDimitry Andric     CodeSize = estimateBranchInst(*I);
1985f757f3fSDimitry Andric   } else {
19906c3fb27SDimitry Andric     C = visit(*User);
20006c3fb27SDimitry Andric     if (!C)
2015f757f3fSDimitry Andric       return {0, 0};
2025f757f3fSDimitry Andric   }
20306c3fb27SDimitry Andric 
2045f757f3fSDimitry Andric   // Even though it doesn't make sense to bind switch and branch instructions
2055f757f3fSDimitry Andric   // with a constant, unlike any other instruction type, it prevents estimating
2065f757f3fSDimitry Andric   // their bonus multiple times.
20706c3fb27SDimitry Andric   KnownConstants.insert({User, C});
20806c3fb27SDimitry Andric 
2095f757f3fSDimitry Andric   CodeSize += TTI.getInstructionCost(User, TargetTransformInfo::TCK_CodeSize);
2105f757f3fSDimitry Andric 
21106c3fb27SDimitry Andric   uint64_t Weight = BFI.getBlockFreq(User->getParent()).getFrequency() /
2125f757f3fSDimitry Andric                     BFI.getEntryFreq().getFrequency();
21306c3fb27SDimitry Andric 
2145f757f3fSDimitry Andric   Cost Latency = Weight *
2155f757f3fSDimitry Andric       TTI.getInstructionCost(User, TargetTransformInfo::TCK_Latency);
21606c3fb27SDimitry Andric 
2175f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "FnSpecialization:     {CodeSize = " << CodeSize
2185f757f3fSDimitry Andric                     << ", Latency = " << Latency << "} for user "
2195f757f3fSDimitry Andric                     << *User << "\n");
22006c3fb27SDimitry Andric 
2215f757f3fSDimitry Andric   Bonus B(CodeSize, Latency);
22206c3fb27SDimitry Andric   for (auto *U : User->users())
22306c3fb27SDimitry Andric     if (auto *UI = dyn_cast<Instruction>(U))
2245f757f3fSDimitry Andric       if (UI != User && isBlockExecutable(UI->getParent()))
2255f757f3fSDimitry Andric         B += getUserBonus(UI, User, C);
22606c3fb27SDimitry Andric 
2275f757f3fSDimitry Andric   return B;
22806c3fb27SDimitry Andric }
22906c3fb27SDimitry Andric 
23006c3fb27SDimitry Andric Cost InstCostVisitor::estimateSwitchInst(SwitchInst &I) {
2315f757f3fSDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
2325f757f3fSDimitry Andric 
23306c3fb27SDimitry Andric   if (I.getCondition() != LastVisited->first)
23406c3fb27SDimitry Andric     return 0;
23506c3fb27SDimitry Andric 
23606c3fb27SDimitry Andric   auto *C = dyn_cast<ConstantInt>(LastVisited->second);
23706c3fb27SDimitry Andric   if (!C)
23806c3fb27SDimitry Andric     return 0;
23906c3fb27SDimitry Andric 
24006c3fb27SDimitry Andric   BasicBlock *Succ = I.findCaseValue(C)->getCaseSuccessor();
24106c3fb27SDimitry Andric   // Initialize the worklist with the dead basic blocks. These are the
24206c3fb27SDimitry Andric   // destination labels which are different from the one corresponding
24306c3fb27SDimitry Andric   // to \p C. They should be executable and have a unique predecessor.
24406c3fb27SDimitry Andric   SmallVector<BasicBlock *> WorkList;
24506c3fb27SDimitry Andric   for (const auto &Case : I.cases()) {
24606c3fb27SDimitry Andric     BasicBlock *BB = Case.getCaseSuccessor();
2475f757f3fSDimitry Andric     if (BB != Succ && isBlockExecutable(BB) &&
2485f757f3fSDimitry Andric         canEliminateSuccessor(I.getParent(), BB, DeadBlocks))
24906c3fb27SDimitry Andric       WorkList.push_back(BB);
25006c3fb27SDimitry Andric   }
25106c3fb27SDimitry Andric 
2525f757f3fSDimitry Andric   return estimateBasicBlocks(WorkList);
25306c3fb27SDimitry Andric }
25406c3fb27SDimitry Andric 
25506c3fb27SDimitry Andric Cost InstCostVisitor::estimateBranchInst(BranchInst &I) {
2565f757f3fSDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
2575f757f3fSDimitry Andric 
25806c3fb27SDimitry Andric   if (I.getCondition() != LastVisited->first)
25906c3fb27SDimitry Andric     return 0;
26006c3fb27SDimitry Andric 
26106c3fb27SDimitry Andric   BasicBlock *Succ = I.getSuccessor(LastVisited->second->isOneValue());
26206c3fb27SDimitry Andric   // Initialize the worklist with the dead successor as long as
26306c3fb27SDimitry Andric   // it is executable and has a unique predecessor.
26406c3fb27SDimitry Andric   SmallVector<BasicBlock *> WorkList;
2655f757f3fSDimitry Andric   if (isBlockExecutable(Succ) &&
2665f757f3fSDimitry Andric       canEliminateSuccessor(I.getParent(), Succ, DeadBlocks))
26706c3fb27SDimitry Andric     WorkList.push_back(Succ);
26806c3fb27SDimitry Andric 
2695f757f3fSDimitry Andric   return estimateBasicBlocks(WorkList);
2705f757f3fSDimitry Andric }
2715f757f3fSDimitry Andric 
2725f757f3fSDimitry Andric bool InstCostVisitor::discoverTransitivelyIncomingValues(
2735f757f3fSDimitry Andric     Constant *Const, PHINode *Root, DenseSet<PHINode *> &TransitivePHIs) {
2745f757f3fSDimitry Andric 
2755f757f3fSDimitry Andric   SmallVector<PHINode *, 64> WorkList;
2765f757f3fSDimitry Andric   WorkList.push_back(Root);
2775f757f3fSDimitry Andric   unsigned Iter = 0;
2785f757f3fSDimitry Andric 
2795f757f3fSDimitry Andric   while (!WorkList.empty()) {
2805f757f3fSDimitry Andric     PHINode *PN = WorkList.pop_back_val();
2815f757f3fSDimitry Andric 
2825f757f3fSDimitry Andric     if (++Iter > MaxDiscoveryIterations ||
2835f757f3fSDimitry Andric         PN->getNumIncomingValues() > MaxIncomingPhiValues)
2845f757f3fSDimitry Andric       return false;
2855f757f3fSDimitry Andric 
2865f757f3fSDimitry Andric     if (!TransitivePHIs.insert(PN).second)
2875f757f3fSDimitry Andric       continue;
2885f757f3fSDimitry Andric 
2895f757f3fSDimitry Andric     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2905f757f3fSDimitry Andric       Value *V = PN->getIncomingValue(I);
2915f757f3fSDimitry Andric 
2925f757f3fSDimitry Andric       // Disregard self-references and dead incoming values.
2935f757f3fSDimitry Andric       if (auto *Inst = dyn_cast<Instruction>(V))
2945f757f3fSDimitry Andric         if (Inst == PN || DeadBlocks.contains(PN->getIncomingBlock(I)))
2955f757f3fSDimitry Andric           continue;
2965f757f3fSDimitry Andric 
2975f757f3fSDimitry Andric       if (Constant *C = findConstantFor(V, KnownConstants)) {
2985f757f3fSDimitry Andric         // Not all incoming values are the same constant. Bail immediately.
2995f757f3fSDimitry Andric         if (C != Const)
3005f757f3fSDimitry Andric           return false;
3015f757f3fSDimitry Andric         continue;
3025f757f3fSDimitry Andric       }
3035f757f3fSDimitry Andric 
3045f757f3fSDimitry Andric       if (auto *Phi = dyn_cast<PHINode>(V)) {
3055f757f3fSDimitry Andric         WorkList.push_back(Phi);
3065f757f3fSDimitry Andric         continue;
3075f757f3fSDimitry Andric       }
3085f757f3fSDimitry Andric 
3095f757f3fSDimitry Andric       // We can't reason about anything else.
3105f757f3fSDimitry Andric       return false;
3115f757f3fSDimitry Andric     }
3125f757f3fSDimitry Andric   }
3135f757f3fSDimitry Andric   return true;
3145f757f3fSDimitry Andric }
3155f757f3fSDimitry Andric 
3165f757f3fSDimitry Andric Constant *InstCostVisitor::visitPHINode(PHINode &I) {
3175f757f3fSDimitry Andric   if (I.getNumIncomingValues() > MaxIncomingPhiValues)
3185f757f3fSDimitry Andric     return nullptr;
3195f757f3fSDimitry Andric 
3205f757f3fSDimitry Andric   bool Inserted = VisitedPHIs.insert(&I).second;
3215f757f3fSDimitry Andric   Constant *Const = nullptr;
3225f757f3fSDimitry Andric   bool HaveSeenIncomingPHI = false;
3235f757f3fSDimitry Andric 
3245f757f3fSDimitry Andric   for (unsigned Idx = 0, E = I.getNumIncomingValues(); Idx != E; ++Idx) {
3255f757f3fSDimitry Andric     Value *V = I.getIncomingValue(Idx);
3265f757f3fSDimitry Andric 
3275f757f3fSDimitry Andric     // Disregard self-references and dead incoming values.
3285f757f3fSDimitry Andric     if (auto *Inst = dyn_cast<Instruction>(V))
3295f757f3fSDimitry Andric       if (Inst == &I || DeadBlocks.contains(I.getIncomingBlock(Idx)))
3305f757f3fSDimitry Andric         continue;
3315f757f3fSDimitry Andric 
3325f757f3fSDimitry Andric     if (Constant *C = findConstantFor(V, KnownConstants)) {
3335f757f3fSDimitry Andric       if (!Const)
3345f757f3fSDimitry Andric         Const = C;
3355f757f3fSDimitry Andric       // Not all incoming values are the same constant. Bail immediately.
3365f757f3fSDimitry Andric       if (C != Const)
3375f757f3fSDimitry Andric         return nullptr;
3385f757f3fSDimitry Andric       continue;
3395f757f3fSDimitry Andric     }
3405f757f3fSDimitry Andric 
3415f757f3fSDimitry Andric     if (Inserted) {
3425f757f3fSDimitry Andric       // First time we are seeing this phi. We will retry later, after
3435f757f3fSDimitry Andric       // all the constant arguments have been propagated. Bail for now.
3445f757f3fSDimitry Andric       PendingPHIs.push_back(&I);
3455f757f3fSDimitry Andric       return nullptr;
3465f757f3fSDimitry Andric     }
3475f757f3fSDimitry Andric 
3485f757f3fSDimitry Andric     if (isa<PHINode>(V)) {
3495f757f3fSDimitry Andric       // Perhaps it is a Transitive Phi. We will confirm later.
3505f757f3fSDimitry Andric       HaveSeenIncomingPHI = true;
3515f757f3fSDimitry Andric       continue;
3525f757f3fSDimitry Andric     }
3535f757f3fSDimitry Andric 
3545f757f3fSDimitry Andric     // We can't reason about anything else.
3555f757f3fSDimitry Andric     return nullptr;
3565f757f3fSDimitry Andric   }
3575f757f3fSDimitry Andric 
3585f757f3fSDimitry Andric   if (!Const)
3595f757f3fSDimitry Andric     return nullptr;
3605f757f3fSDimitry Andric 
3615f757f3fSDimitry Andric   if (!HaveSeenIncomingPHI)
3625f757f3fSDimitry Andric     return Const;
3635f757f3fSDimitry Andric 
3645f757f3fSDimitry Andric   DenseSet<PHINode *> TransitivePHIs;
3655f757f3fSDimitry Andric   if (!discoverTransitivelyIncomingValues(Const, &I, TransitivePHIs))
3665f757f3fSDimitry Andric     return nullptr;
3675f757f3fSDimitry Andric 
3685f757f3fSDimitry Andric   return Const;
36906c3fb27SDimitry Andric }
37006c3fb27SDimitry Andric 
37106c3fb27SDimitry Andric Constant *InstCostVisitor::visitFreezeInst(FreezeInst &I) {
3725f757f3fSDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
3735f757f3fSDimitry Andric 
37406c3fb27SDimitry Andric   if (isGuaranteedNotToBeUndefOrPoison(LastVisited->second))
37506c3fb27SDimitry Andric     return LastVisited->second;
37606c3fb27SDimitry Andric   return nullptr;
37706c3fb27SDimitry Andric }
37806c3fb27SDimitry Andric 
37906c3fb27SDimitry Andric Constant *InstCostVisitor::visitCallBase(CallBase &I) {
38006c3fb27SDimitry Andric   Function *F = I.getCalledFunction();
38106c3fb27SDimitry Andric   if (!F || !canConstantFoldCallTo(&I, F))
38206c3fb27SDimitry Andric     return nullptr;
38306c3fb27SDimitry Andric 
38406c3fb27SDimitry Andric   SmallVector<Constant *, 8> Operands;
38506c3fb27SDimitry Andric   Operands.reserve(I.getNumOperands());
38606c3fb27SDimitry Andric 
38706c3fb27SDimitry Andric   for (unsigned Idx = 0, E = I.getNumOperands() - 1; Idx != E; ++Idx) {
38806c3fb27SDimitry Andric     Value *V = I.getOperand(Idx);
38906c3fb27SDimitry Andric     Constant *C = findConstantFor(V, KnownConstants);
39006c3fb27SDimitry Andric     if (!C)
39106c3fb27SDimitry Andric       return nullptr;
39206c3fb27SDimitry Andric     Operands.push_back(C);
39306c3fb27SDimitry Andric   }
39406c3fb27SDimitry Andric 
39506c3fb27SDimitry Andric   auto Ops = ArrayRef(Operands.begin(), Operands.end());
39606c3fb27SDimitry Andric   return ConstantFoldCall(&I, F, Ops);
39706c3fb27SDimitry Andric }
39806c3fb27SDimitry Andric 
39906c3fb27SDimitry Andric Constant *InstCostVisitor::visitLoadInst(LoadInst &I) {
4005f757f3fSDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
4015f757f3fSDimitry Andric 
40206c3fb27SDimitry Andric   if (isa<ConstantPointerNull>(LastVisited->second))
40306c3fb27SDimitry Andric     return nullptr;
40406c3fb27SDimitry Andric   return ConstantFoldLoadFromConstPtr(LastVisited->second, I.getType(), DL);
40506c3fb27SDimitry Andric }
40606c3fb27SDimitry Andric 
40706c3fb27SDimitry Andric Constant *InstCostVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
40806c3fb27SDimitry Andric   SmallVector<Constant *, 8> Operands;
40906c3fb27SDimitry Andric   Operands.reserve(I.getNumOperands());
41006c3fb27SDimitry Andric 
41106c3fb27SDimitry Andric   for (unsigned Idx = 0, E = I.getNumOperands(); Idx != E; ++Idx) {
41206c3fb27SDimitry Andric     Value *V = I.getOperand(Idx);
41306c3fb27SDimitry Andric     Constant *C = findConstantFor(V, KnownConstants);
41406c3fb27SDimitry Andric     if (!C)
41506c3fb27SDimitry Andric       return nullptr;
41606c3fb27SDimitry Andric     Operands.push_back(C);
41706c3fb27SDimitry Andric   }
41806c3fb27SDimitry Andric 
41906c3fb27SDimitry Andric   auto Ops = ArrayRef(Operands.begin(), Operands.end());
42006c3fb27SDimitry Andric   return ConstantFoldInstOperands(&I, Ops, DL);
42106c3fb27SDimitry Andric }
42206c3fb27SDimitry Andric 
42306c3fb27SDimitry Andric Constant *InstCostVisitor::visitSelectInst(SelectInst &I) {
4245f757f3fSDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
4255f757f3fSDimitry Andric 
42606c3fb27SDimitry Andric   if (I.getCondition() != LastVisited->first)
42706c3fb27SDimitry Andric     return nullptr;
42806c3fb27SDimitry Andric 
42906c3fb27SDimitry Andric   Value *V = LastVisited->second->isZeroValue() ? I.getFalseValue()
43006c3fb27SDimitry Andric                                                 : I.getTrueValue();
43106c3fb27SDimitry Andric   Constant *C = findConstantFor(V, KnownConstants);
43206c3fb27SDimitry Andric   return C;
43306c3fb27SDimitry Andric }
43406c3fb27SDimitry Andric 
43506c3fb27SDimitry Andric Constant *InstCostVisitor::visitCastInst(CastInst &I) {
43606c3fb27SDimitry Andric   return ConstantFoldCastOperand(I.getOpcode(), LastVisited->second,
43706c3fb27SDimitry Andric                                  I.getType(), DL);
43806c3fb27SDimitry Andric }
43906c3fb27SDimitry Andric 
44006c3fb27SDimitry Andric Constant *InstCostVisitor::visitCmpInst(CmpInst &I) {
4415f757f3fSDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
4425f757f3fSDimitry Andric 
44306c3fb27SDimitry Andric   bool Swap = I.getOperand(1) == LastVisited->first;
44406c3fb27SDimitry Andric   Value *V = Swap ? I.getOperand(0) : I.getOperand(1);
44506c3fb27SDimitry Andric   Constant *Other = findConstantFor(V, KnownConstants);
44606c3fb27SDimitry Andric   if (!Other)
44706c3fb27SDimitry Andric     return nullptr;
44806c3fb27SDimitry Andric 
44906c3fb27SDimitry Andric   Constant *Const = LastVisited->second;
45006c3fb27SDimitry Andric   return Swap ?
45106c3fb27SDimitry Andric         ConstantFoldCompareInstOperands(I.getPredicate(), Other, Const, DL)
45206c3fb27SDimitry Andric       : ConstantFoldCompareInstOperands(I.getPredicate(), Const, Other, DL);
45306c3fb27SDimitry Andric }
45406c3fb27SDimitry Andric 
45506c3fb27SDimitry Andric Constant *InstCostVisitor::visitUnaryOperator(UnaryOperator &I) {
4565f757f3fSDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
4575f757f3fSDimitry Andric 
45806c3fb27SDimitry Andric   return ConstantFoldUnaryOpOperand(I.getOpcode(), LastVisited->second, DL);
45906c3fb27SDimitry Andric }
46006c3fb27SDimitry Andric 
46106c3fb27SDimitry Andric Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) {
4625f757f3fSDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
4635f757f3fSDimitry Andric 
46406c3fb27SDimitry Andric   bool Swap = I.getOperand(1) == LastVisited->first;
46506c3fb27SDimitry Andric   Value *V = Swap ? I.getOperand(0) : I.getOperand(1);
46606c3fb27SDimitry Andric   Constant *Other = findConstantFor(V, KnownConstants);
46706c3fb27SDimitry Andric   if (!Other)
46806c3fb27SDimitry Andric     return nullptr;
46906c3fb27SDimitry Andric 
47006c3fb27SDimitry Andric   Constant *Const = LastVisited->second;
47106c3fb27SDimitry Andric   return dyn_cast_or_null<Constant>(Swap ?
47206c3fb27SDimitry Andric         simplifyBinOp(I.getOpcode(), Other, Const, SimplifyQuery(DL))
47306c3fb27SDimitry Andric       : simplifyBinOp(I.getOpcode(), Const, Other, SimplifyQuery(DL)));
47406c3fb27SDimitry Andric }
475349cc55cSDimitry Andric 
476bdd1243dSDimitry Andric Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca,
477bdd1243dSDimitry Andric                                                    CallInst *Call) {
478349cc55cSDimitry Andric   Value *StoreValue = nullptr;
479349cc55cSDimitry Andric   for (auto *User : Alloca->users()) {
480349cc55cSDimitry Andric     // We can't use llvm::isAllocaPromotable() as that would fail because of
481349cc55cSDimitry Andric     // the usage in the CallInst, which is what we check here.
482349cc55cSDimitry Andric     if (User == Call)
483349cc55cSDimitry Andric       continue;
484349cc55cSDimitry Andric     if (auto *Bitcast = dyn_cast<BitCastInst>(User)) {
485349cc55cSDimitry Andric       if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call)
486349cc55cSDimitry Andric         return nullptr;
487349cc55cSDimitry Andric       continue;
488349cc55cSDimitry Andric     }
489349cc55cSDimitry Andric 
490349cc55cSDimitry Andric     if (auto *Store = dyn_cast<StoreInst>(User)) {
491349cc55cSDimitry Andric       // This is a duplicate store, bail out.
492349cc55cSDimitry Andric       if (StoreValue || Store->isVolatile())
493349cc55cSDimitry Andric         return nullptr;
494349cc55cSDimitry Andric       StoreValue = Store->getValueOperand();
495349cc55cSDimitry Andric       continue;
496349cc55cSDimitry Andric     }
497349cc55cSDimitry Andric     // Bail if there is any other unknown usage.
498349cc55cSDimitry Andric     return nullptr;
499349cc55cSDimitry Andric   }
50006c3fb27SDimitry Andric 
50106c3fb27SDimitry Andric   if (!StoreValue)
50206c3fb27SDimitry Andric     return nullptr;
50306c3fb27SDimitry Andric 
504bdd1243dSDimitry Andric   return getCandidateConstant(StoreValue);
505349cc55cSDimitry Andric }
506349cc55cSDimitry Andric 
507349cc55cSDimitry Andric // A constant stack value is an AllocaInst that has a single constant
508349cc55cSDimitry Andric // value stored to it. Return this constant if such an alloca stack value
509349cc55cSDimitry Andric // is a function argument.
510bdd1243dSDimitry Andric Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call,
511bdd1243dSDimitry Andric                                                      Value *Val) {
512349cc55cSDimitry Andric   if (!Val)
513349cc55cSDimitry Andric     return nullptr;
514349cc55cSDimitry Andric   Val = Val->stripPointerCasts();
515349cc55cSDimitry Andric   if (auto *ConstVal = dyn_cast<ConstantInt>(Val))
516349cc55cSDimitry Andric     return ConstVal;
517349cc55cSDimitry Andric   auto *Alloca = dyn_cast<AllocaInst>(Val);
518349cc55cSDimitry Andric   if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())
519349cc55cSDimitry Andric     return nullptr;
520349cc55cSDimitry Andric   return getPromotableAlloca(Alloca, Call);
521349cc55cSDimitry Andric }
522349cc55cSDimitry Andric 
523349cc55cSDimitry Andric // To support specializing recursive functions, it is important to propagate
524349cc55cSDimitry Andric // constant arguments because after a first iteration of specialisation, a
525349cc55cSDimitry Andric // reduced example may look like this:
526349cc55cSDimitry Andric //
527349cc55cSDimitry Andric //     define internal void @RecursiveFn(i32* arg1) {
528349cc55cSDimitry Andric //       %temp = alloca i32, align 4
529349cc55cSDimitry Andric //       store i32 2 i32* %temp, align 4
530349cc55cSDimitry Andric //       call void @RecursiveFn.1(i32* nonnull %temp)
531349cc55cSDimitry Andric //       ret void
532349cc55cSDimitry Andric //     }
533349cc55cSDimitry Andric //
534349cc55cSDimitry Andric // Before a next iteration, we need to propagate the constant like so
535349cc55cSDimitry Andric // which allows further specialization in next iterations.
536349cc55cSDimitry Andric //
537349cc55cSDimitry Andric //     @funcspec.arg = internal constant i32 2
538349cc55cSDimitry Andric //
539349cc55cSDimitry Andric //     define internal void @someFunc(i32* arg1) {
540349cc55cSDimitry Andric //       call void @otherFunc(i32* nonnull @funcspec.arg)
541349cc55cSDimitry Andric //       ret void
542349cc55cSDimitry Andric //     }
543349cc55cSDimitry Andric //
54406c3fb27SDimitry Andric // See if there are any new constant values for the callers of \p F via
54506c3fb27SDimitry Andric // stack variables and promote them to global variables.
54606c3fb27SDimitry Andric void FunctionSpecializer::promoteConstantStackValues(Function *F) {
54706c3fb27SDimitry Andric   for (User *U : F->users()) {
548349cc55cSDimitry Andric 
54906c3fb27SDimitry Andric     auto *Call = dyn_cast<CallInst>(U);
550349cc55cSDimitry Andric     if (!Call)
55181ad6265SDimitry Andric       continue;
55281ad6265SDimitry Andric 
553bdd1243dSDimitry Andric     if (!Solver.isBlockExecutable(Call->getParent()))
554bdd1243dSDimitry Andric       continue;
555bdd1243dSDimitry Andric 
55681ad6265SDimitry Andric     for (const Use &U : Call->args()) {
55781ad6265SDimitry Andric       unsigned Idx = Call->getArgOperandNo(&U);
55881ad6265SDimitry Andric       Value *ArgOp = Call->getArgOperand(Idx);
55981ad6265SDimitry Andric       Type *ArgOpType = ArgOp->getType();
56081ad6265SDimitry Andric 
56181ad6265SDimitry Andric       if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy())
56281ad6265SDimitry Andric         continue;
56381ad6265SDimitry Andric 
564bdd1243dSDimitry Andric       auto *ConstVal = getConstantStackValue(Call, ArgOp);
565349cc55cSDimitry Andric       if (!ConstVal)
56681ad6265SDimitry Andric         continue;
567349cc55cSDimitry Andric 
568349cc55cSDimitry Andric       Value *GV = new GlobalVariable(M, ConstVal->getType(), true,
569349cc55cSDimitry Andric                                      GlobalValue::InternalLinkage, ConstVal,
5705f757f3fSDimitry Andric                                      "specialized.arg." + Twine(++NGlobals));
57181ad6265SDimitry Andric       Call->setArgOperand(Idx, GV);
572349cc55cSDimitry Andric     }
573349cc55cSDimitry Andric   }
574349cc55cSDimitry Andric }
575349cc55cSDimitry Andric 
576349cc55cSDimitry Andric // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics
577bdd1243dSDimitry Andric // interfere with the promoteConstantStackValues() optimization.
578349cc55cSDimitry Andric static void removeSSACopy(Function &F) {
579349cc55cSDimitry Andric   for (BasicBlock &BB : F) {
580349cc55cSDimitry Andric     for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
581349cc55cSDimitry Andric       auto *II = dyn_cast<IntrinsicInst>(&Inst);
582349cc55cSDimitry Andric       if (!II)
583349cc55cSDimitry Andric         continue;
584349cc55cSDimitry Andric       if (II->getIntrinsicID() != Intrinsic::ssa_copy)
585349cc55cSDimitry Andric         continue;
586349cc55cSDimitry Andric       Inst.replaceAllUsesWith(II->getOperand(0));
587349cc55cSDimitry Andric       Inst.eraseFromParent();
588349cc55cSDimitry Andric     }
589349cc55cSDimitry Andric   }
590349cc55cSDimitry Andric }
591349cc55cSDimitry Andric 
592bdd1243dSDimitry Andric /// Remove any ssa_copy intrinsics that may have been introduced.
593bdd1243dSDimitry Andric void FunctionSpecializer::cleanUpSSA() {
59406c3fb27SDimitry Andric   for (Function *F : Specializations)
595bdd1243dSDimitry Andric     removeSSACopy(*F);
596349cc55cSDimitry Andric }
597349cc55cSDimitry Andric 
598fe6060f1SDimitry Andric 
599bdd1243dSDimitry Andric template <> struct llvm::DenseMapInfo<SpecSig> {
600bdd1243dSDimitry Andric   static inline SpecSig getEmptyKey() { return {~0U, {}}; }
601fe6060f1SDimitry Andric 
602bdd1243dSDimitry Andric   static inline SpecSig getTombstoneKey() { return {~1U, {}}; }
603fe6060f1SDimitry Andric 
604bdd1243dSDimitry Andric   static unsigned getHashValue(const SpecSig &S) {
605bdd1243dSDimitry Andric     return static_cast<unsigned>(hash_value(S));
60681ad6265SDimitry Andric   }
60781ad6265SDimitry Andric 
608bdd1243dSDimitry Andric   static bool isEqual(const SpecSig &LHS, const SpecSig &RHS) {
609bdd1243dSDimitry Andric     return LHS == RHS;
610bdd1243dSDimitry Andric   }
611bdd1243dSDimitry Andric };
612bdd1243dSDimitry Andric 
61306c3fb27SDimitry Andric FunctionSpecializer::~FunctionSpecializer() {
61406c3fb27SDimitry Andric   LLVM_DEBUG(
61506c3fb27SDimitry Andric     if (NumSpecsCreated > 0)
61606c3fb27SDimitry Andric       dbgs() << "FnSpecialization: Created " << NumSpecsCreated
61706c3fb27SDimitry Andric              << " specializations in module " << M.getName() << "\n");
61806c3fb27SDimitry Andric   // Eliminate dead code.
61906c3fb27SDimitry Andric   removeDeadFunctions();
62006c3fb27SDimitry Andric   cleanUpSSA();
62106c3fb27SDimitry Andric }
62206c3fb27SDimitry Andric 
623fe6060f1SDimitry Andric /// Attempt to specialize functions in the module to enable constant
624fe6060f1SDimitry Andric /// propagation across function boundaries.
625fe6060f1SDimitry Andric ///
626fe6060f1SDimitry Andric /// \returns true if at least one function is specialized.
627bdd1243dSDimitry Andric bool FunctionSpecializer::run() {
628bdd1243dSDimitry Andric   // Find possible specializations for each function.
629bdd1243dSDimitry Andric   SpecMap SM;
630bdd1243dSDimitry Andric   SmallVector<Spec, 32> AllSpecs;
631bdd1243dSDimitry Andric   unsigned NumCandidates = 0;
632bdd1243dSDimitry Andric   for (Function &F : M) {
633bdd1243dSDimitry Andric     if (!isCandidateFunction(&F))
6340eae32dcSDimitry Andric       continue;
6350eae32dcSDimitry Andric 
63606c3fb27SDimitry Andric     auto [It, Inserted] = FunctionMetrics.try_emplace(&F);
63706c3fb27SDimitry Andric     CodeMetrics &Metrics = It->second;
63806c3fb27SDimitry Andric     //Analyze the function.
63906c3fb27SDimitry Andric     if (Inserted) {
64006c3fb27SDimitry Andric       SmallPtrSet<const Value *, 32> EphValues;
64106c3fb27SDimitry Andric       CodeMetrics::collectEphemeralValues(&F, &GetAC(F), EphValues);
64206c3fb27SDimitry Andric       for (BasicBlock &BB : F)
64306c3fb27SDimitry Andric         Metrics.analyzeBasicBlock(&BB, GetTTI(F), EphValues);
6440eae32dcSDimitry Andric     }
6450eae32dcSDimitry Andric 
64606c3fb27SDimitry Andric     // If the code metrics reveal that we shouldn't duplicate the function,
64706c3fb27SDimitry Andric     // or if the code size implies that this function is easy to get inlined,
64806c3fb27SDimitry Andric     // then we shouldn't specialize it.
64906c3fb27SDimitry Andric     if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() ||
65006c3fb27SDimitry Andric         (!ForceSpecialization && !F.hasFnAttribute(Attribute::NoInline) &&
65106c3fb27SDimitry Andric          Metrics.NumInsts < MinFunctionSize))
65206c3fb27SDimitry Andric       continue;
65381ad6265SDimitry Andric 
65406c3fb27SDimitry Andric     // TODO: For now only consider recursive functions when running multiple
65506c3fb27SDimitry Andric     // times. This should change if specialization on literal constants gets
65606c3fb27SDimitry Andric     // enabled.
65706c3fb27SDimitry Andric     if (!Inserted && !Metrics.isRecursive && !SpecializeLiteralConstant)
65806c3fb27SDimitry Andric       continue;
65906c3fb27SDimitry Andric 
6605f757f3fSDimitry Andric     int64_t Sz = *Metrics.NumInsts.getValue();
6615f757f3fSDimitry Andric     assert(Sz > 0 && "CodeSize should be positive");
6625f757f3fSDimitry Andric     // It is safe to down cast from int64_t, NumInsts is always positive.
6635f757f3fSDimitry Andric     unsigned FuncSize = static_cast<unsigned>(Sz);
6645f757f3fSDimitry Andric 
66506c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for "
6665f757f3fSDimitry Andric                       << F.getName() << " is " << FuncSize << "\n");
66706c3fb27SDimitry Andric 
66806c3fb27SDimitry Andric     if (Inserted && Metrics.isRecursive)
66906c3fb27SDimitry Andric       promoteConstantStackValues(&F);
67006c3fb27SDimitry Andric 
6715f757f3fSDimitry Andric     if (!findSpecializations(&F, FuncSize, AllSpecs, SM)) {
672bdd1243dSDimitry Andric       LLVM_DEBUG(
673bdd1243dSDimitry Andric           dbgs() << "FnSpecialization: No possible specializations found for "
674bdd1243dSDimitry Andric                  << F.getName() << "\n");
6750eae32dcSDimitry Andric       continue;
6760eae32dcSDimitry Andric     }
6770eae32dcSDimitry Andric 
678bdd1243dSDimitry Andric     ++NumCandidates;
679fe6060f1SDimitry Andric   }
680fe6060f1SDimitry Andric 
681bdd1243dSDimitry Andric   if (!NumCandidates) {
682bdd1243dSDimitry Andric     LLVM_DEBUG(
683bdd1243dSDimitry Andric         dbgs()
684bdd1243dSDimitry Andric         << "FnSpecialization: No possible specializations found in module\n");
685bdd1243dSDimitry Andric     return false;
686bdd1243dSDimitry Andric   }
687bdd1243dSDimitry Andric 
688bdd1243dSDimitry Andric   // Choose the most profitable specialisations, which fit in the module
689bdd1243dSDimitry Andric   // specialization budget, which is derived from maximum number of
690bdd1243dSDimitry Andric   // specializations per specialization candidate function.
69106c3fb27SDimitry Andric   auto CompareScore = [&AllSpecs](unsigned I, unsigned J) {
692*0fca6ea1SDimitry Andric     if (AllSpecs[I].Score != AllSpecs[J].Score)
69306c3fb27SDimitry Andric       return AllSpecs[I].Score > AllSpecs[J].Score;
694*0fca6ea1SDimitry Andric     return I > J;
695bdd1243dSDimitry Andric   };
696bdd1243dSDimitry Andric   const unsigned NSpecs =
69706c3fb27SDimitry Andric       std::min(NumCandidates * MaxClones, unsigned(AllSpecs.size()));
698bdd1243dSDimitry Andric   SmallVector<unsigned> BestSpecs(NSpecs + 1);
699bdd1243dSDimitry Andric   std::iota(BestSpecs.begin(), BestSpecs.begin() + NSpecs, 0);
700bdd1243dSDimitry Andric   if (AllSpecs.size() > NSpecs) {
701bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed "
702bdd1243dSDimitry Andric                       << "the maximum number of clones threshold.\n"
703bdd1243dSDimitry Andric                       << "FnSpecialization: Specializing the "
704bdd1243dSDimitry Andric                       << NSpecs
705bdd1243dSDimitry Andric                       << " most profitable candidates.\n");
70606c3fb27SDimitry Andric     std::make_heap(BestSpecs.begin(), BestSpecs.begin() + NSpecs, CompareScore);
707bdd1243dSDimitry Andric     for (unsigned I = NSpecs, N = AllSpecs.size(); I < N; ++I) {
708bdd1243dSDimitry Andric       BestSpecs[NSpecs] = I;
70906c3fb27SDimitry Andric       std::push_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
71006c3fb27SDimitry Andric       std::pop_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
711bdd1243dSDimitry Andric     }
712bdd1243dSDimitry Andric   }
713bdd1243dSDimitry Andric 
714bdd1243dSDimitry Andric   LLVM_DEBUG(dbgs() << "FnSpecialization: List of specializations \n";
715bdd1243dSDimitry Andric              for (unsigned I = 0; I < NSpecs; ++I) {
716bdd1243dSDimitry Andric                const Spec &S = AllSpecs[BestSpecs[I]];
717bdd1243dSDimitry Andric                dbgs() << "FnSpecialization: Function " << S.F->getName()
71806c3fb27SDimitry Andric                       << " , score " << S.Score << "\n";
719bdd1243dSDimitry Andric                for (const ArgInfo &Arg : S.Sig.Args)
720bdd1243dSDimitry Andric                  dbgs() << "FnSpecialization:   FormalArg = "
721bdd1243dSDimitry Andric                         << Arg.Formal->getNameOrAsOperand()
722bdd1243dSDimitry Andric                         << ", ActualArg = " << Arg.Actual->getNameOrAsOperand()
723bdd1243dSDimitry Andric                         << "\n";
724bdd1243dSDimitry Andric              });
725bdd1243dSDimitry Andric 
726bdd1243dSDimitry Andric   // Create the chosen specializations.
727bdd1243dSDimitry Andric   SmallPtrSet<Function *, 8> OriginalFuncs;
728bdd1243dSDimitry Andric   SmallVector<Function *> Clones;
729bdd1243dSDimitry Andric   for (unsigned I = 0; I < NSpecs; ++I) {
730bdd1243dSDimitry Andric     Spec &S = AllSpecs[BestSpecs[I]];
731bdd1243dSDimitry Andric     S.Clone = createSpecialization(S.F, S.Sig);
732bdd1243dSDimitry Andric 
733bdd1243dSDimitry Andric     // Update the known call sites to call the clone.
734bdd1243dSDimitry Andric     for (CallBase *Call : S.CallSites) {
735bdd1243dSDimitry Andric       LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call
736bdd1243dSDimitry Andric                         << " to call " << S.Clone->getName() << "\n");
737bdd1243dSDimitry Andric       Call->setCalledFunction(S.Clone);
738bdd1243dSDimitry Andric     }
739bdd1243dSDimitry Andric 
740bdd1243dSDimitry Andric     Clones.push_back(S.Clone);
741bdd1243dSDimitry Andric     OriginalFuncs.insert(S.F);
742bdd1243dSDimitry Andric   }
743bdd1243dSDimitry Andric 
744bdd1243dSDimitry Andric   Solver.solveWhileResolvedUndefsIn(Clones);
745bdd1243dSDimitry Andric 
746bdd1243dSDimitry Andric   // Update the rest of the call sites - these are the recursive calls, calls
747bdd1243dSDimitry Andric   // to discarded specialisations and calls that may match a specialisation
748bdd1243dSDimitry Andric   // after the solver runs.
749bdd1243dSDimitry Andric   for (Function *F : OriginalFuncs) {
750bdd1243dSDimitry Andric     auto [Begin, End] = SM[F];
751bdd1243dSDimitry Andric     updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End);
752bdd1243dSDimitry Andric   }
753bdd1243dSDimitry Andric 
75406c3fb27SDimitry Andric   for (Function *F : Clones) {
75506c3fb27SDimitry Andric     if (F->getReturnType()->isVoidTy())
75606c3fb27SDimitry Andric       continue;
75706c3fb27SDimitry Andric     if (F->getReturnType()->isStructTy()) {
75806c3fb27SDimitry Andric       auto *STy = cast<StructType>(F->getReturnType());
75906c3fb27SDimitry Andric       if (!Solver.isStructLatticeConstant(F, STy))
76006c3fb27SDimitry Andric         continue;
76106c3fb27SDimitry Andric     } else {
76206c3fb27SDimitry Andric       auto It = Solver.getTrackedRetVals().find(F);
76306c3fb27SDimitry Andric       assert(It != Solver.getTrackedRetVals().end() &&
76406c3fb27SDimitry Andric              "Return value ought to be tracked");
76506c3fb27SDimitry Andric       if (SCCPSolver::isOverdefined(It->second))
76606c3fb27SDimitry Andric         continue;
76706c3fb27SDimitry Andric     }
76806c3fb27SDimitry Andric     for (User *U : F->users()) {
76906c3fb27SDimitry Andric       if (auto *CS = dyn_cast<CallBase>(U)) {
77006c3fb27SDimitry Andric         //The user instruction does not call our function.
77106c3fb27SDimitry Andric         if (CS->getCalledFunction() != F)
77206c3fb27SDimitry Andric           continue;
77306c3fb27SDimitry Andric         Solver.resetLatticeValueFor(CS);
77406c3fb27SDimitry Andric       }
77506c3fb27SDimitry Andric     }
77606c3fb27SDimitry Andric   }
777bdd1243dSDimitry Andric 
77806c3fb27SDimitry Andric   // Rerun the solver to notify the users of the modified callsites.
77906c3fb27SDimitry Andric   Solver.solveWhileResolvedUndefs();
78006c3fb27SDimitry Andric 
78106c3fb27SDimitry Andric   for (Function *F : OriginalFuncs)
78206c3fb27SDimitry Andric     if (FunctionMetrics[F].isRecursive)
78306c3fb27SDimitry Andric       promoteConstantStackValues(F);
78406c3fb27SDimitry Andric 
785bdd1243dSDimitry Andric   return true;
786fe6060f1SDimitry Andric }
787fe6060f1SDimitry Andric 
788bdd1243dSDimitry Andric void FunctionSpecializer::removeDeadFunctions() {
789bdd1243dSDimitry Andric   for (Function *F : FullySpecialized) {
79081ad6265SDimitry Andric     LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function "
79181ad6265SDimitry Andric                       << F->getName() << "\n");
792bdd1243dSDimitry Andric     if (FAM)
793bdd1243dSDimitry Andric       FAM->clear(*F, F->getName());
79481ad6265SDimitry Andric     F->eraseFromParent();
79581ad6265SDimitry Andric   }
79681ad6265SDimitry Andric   FullySpecialized.clear();
79781ad6265SDimitry Andric }
79881ad6265SDimitry Andric 
799349cc55cSDimitry Andric /// Clone the function \p F and remove the ssa_copy intrinsics added by
800349cc55cSDimitry Andric /// the SCCPSolver in the cloned version.
8015f757f3fSDimitry Andric static Function *cloneCandidateFunction(Function *F, unsigned NSpecs) {
802bdd1243dSDimitry Andric   ValueToValueMapTy Mappings;
80381ad6265SDimitry Andric   Function *Clone = CloneFunction(F, Mappings);
8045f757f3fSDimitry Andric   Clone->setName(F->getName() + ".specialized." + Twine(NSpecs));
805349cc55cSDimitry Andric   removeSSACopy(*Clone);
806349cc55cSDimitry Andric   return Clone;
807349cc55cSDimitry Andric }
808349cc55cSDimitry Andric 
8095f757f3fSDimitry Andric bool FunctionSpecializer::findSpecializations(Function *F, unsigned FuncSize,
810bdd1243dSDimitry Andric                                               SmallVectorImpl<Spec> &AllSpecs,
811bdd1243dSDimitry Andric                                               SpecMap &SM) {
812bdd1243dSDimitry Andric   // A mapping from a specialisation signature to the index of the respective
813bdd1243dSDimitry Andric   // entry in the all specialisation array. Used to ensure uniqueness of
814bdd1243dSDimitry Andric   // specialisations.
81506c3fb27SDimitry Andric   DenseMap<SpecSig, unsigned> UniqueSpecs;
816bdd1243dSDimitry Andric 
817bdd1243dSDimitry Andric   // Get a list of interesting arguments.
818bdd1243dSDimitry Andric   SmallVector<Argument *> Args;
819bdd1243dSDimitry Andric   for (Argument &Arg : F->args())
820bdd1243dSDimitry Andric     if (isArgumentInteresting(&Arg))
821bdd1243dSDimitry Andric       Args.push_back(&Arg);
822bdd1243dSDimitry Andric 
823bdd1243dSDimitry Andric   if (Args.empty())
824bdd1243dSDimitry Andric     return false;
825bdd1243dSDimitry Andric 
826bdd1243dSDimitry Andric   for (User *U : F->users()) {
827bdd1243dSDimitry Andric     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
8280eae32dcSDimitry Andric       continue;
829bdd1243dSDimitry Andric     auto &CS = *cast<CallBase>(U);
830bdd1243dSDimitry Andric 
831bdd1243dSDimitry Andric     // The user instruction does not call our function.
832bdd1243dSDimitry Andric     if (CS.getCalledFunction() != F)
833bdd1243dSDimitry Andric       continue;
834bdd1243dSDimitry Andric 
835bdd1243dSDimitry Andric     // If the call site has attribute minsize set, that callsite won't be
836bdd1243dSDimitry Andric     // specialized.
837bdd1243dSDimitry Andric     if (CS.hasFnAttr(Attribute::MinSize))
838bdd1243dSDimitry Andric       continue;
839bdd1243dSDimitry Andric 
840bdd1243dSDimitry Andric     // If the parent of the call site will never be executed, we don't need
841bdd1243dSDimitry Andric     // to worry about the passed value.
842bdd1243dSDimitry Andric     if (!Solver.isBlockExecutable(CS.getParent()))
843bdd1243dSDimitry Andric       continue;
844bdd1243dSDimitry Andric 
845bdd1243dSDimitry Andric     // Examine arguments and create a specialisation candidate from the
846bdd1243dSDimitry Andric     // constant operands of this call site.
847bdd1243dSDimitry Andric     SpecSig S;
848bdd1243dSDimitry Andric     for (Argument *A : Args) {
849bdd1243dSDimitry Andric       Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo()));
850bdd1243dSDimitry Andric       if (!C)
851bdd1243dSDimitry Andric         continue;
852bdd1243dSDimitry Andric       LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument "
853bdd1243dSDimitry Andric                         << A->getName() << " : " << C->getNameOrAsOperand()
854bdd1243dSDimitry Andric                         << "\n");
855bdd1243dSDimitry Andric       S.Args.push_back({A, C});
8560eae32dcSDimitry Andric     }
857fe6060f1SDimitry Andric 
858bdd1243dSDimitry Andric     if (S.Args.empty())
859bdd1243dSDimitry Andric       continue;
8600eae32dcSDimitry Andric 
861bdd1243dSDimitry Andric     // Check if we have encountered the same specialisation already.
86206c3fb27SDimitry Andric     if (auto It = UniqueSpecs.find(S); It != UniqueSpecs.end()) {
863bdd1243dSDimitry Andric       // Existing specialisation. Add the call to the list to rewrite, unless
864bdd1243dSDimitry Andric       // it's a recursive call. A specialisation, generated because of a
865bdd1243dSDimitry Andric       // recursive call may end up as not the best specialisation for all
866bdd1243dSDimitry Andric       // the cloned instances of this call, which result from specialising
867bdd1243dSDimitry Andric       // functions. Hence we don't rewrite the call directly, but match it with
868bdd1243dSDimitry Andric       // the best specialisation once all specialisations are known.
869bdd1243dSDimitry Andric       if (CS.getFunction() == F)
870bdd1243dSDimitry Andric         continue;
871bdd1243dSDimitry Andric       const unsigned Index = It->second;
872bdd1243dSDimitry Andric       AllSpecs[Index].CallSites.push_back(&CS);
873bdd1243dSDimitry Andric     } else {
874bdd1243dSDimitry Andric       // Calculate the specialisation gain.
8755f757f3fSDimitry Andric       Bonus B;
8765f757f3fSDimitry Andric       unsigned Score = 0;
87706c3fb27SDimitry Andric       InstCostVisitor Visitor = getInstCostVisitorFor(F);
8785f757f3fSDimitry Andric       for (ArgInfo &A : S.Args) {
8795f757f3fSDimitry Andric         B += Visitor.getSpecializationBonus(A.Formal, A.Actual);
8805f757f3fSDimitry Andric         Score += getInliningBonus(A.Formal, A.Actual);
8815f757f3fSDimitry Andric       }
8825f757f3fSDimitry Andric       B += Visitor.getBonusFromPendingPHIs();
8835f757f3fSDimitry Andric 
8845f757f3fSDimitry Andric 
8855f757f3fSDimitry Andric       LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization bonus {CodeSize = "
8865f757f3fSDimitry Andric                         << B.CodeSize << ", Latency = " << B.Latency
8875f757f3fSDimitry Andric                         << ", Inlining = " << Score << "}\n");
8885f757f3fSDimitry Andric 
8895f757f3fSDimitry Andric       FunctionGrowth[F] += FuncSize - B.CodeSize;
8905f757f3fSDimitry Andric 
8915f757f3fSDimitry Andric       auto IsProfitable = [](Bonus &B, unsigned Score, unsigned FuncSize,
8925f757f3fSDimitry Andric                              unsigned FuncGrowth) -> bool {
8935f757f3fSDimitry Andric         // No check required.
8945f757f3fSDimitry Andric         if (ForceSpecialization)
8955f757f3fSDimitry Andric           return true;
8965f757f3fSDimitry Andric         // Minimum inlining bonus.
8975f757f3fSDimitry Andric         if (Score > MinInliningBonus * FuncSize / 100)
8985f757f3fSDimitry Andric           return true;
8995f757f3fSDimitry Andric         // Minimum codesize savings.
9005f757f3fSDimitry Andric         if (B.CodeSize < MinCodeSizeSavings * FuncSize / 100)
9015f757f3fSDimitry Andric           return false;
9025f757f3fSDimitry Andric         // Minimum latency savings.
9035f757f3fSDimitry Andric         if (B.Latency < MinLatencySavings * FuncSize / 100)
9045f757f3fSDimitry Andric           return false;
9055f757f3fSDimitry Andric         // Maximum codesize growth.
9065f757f3fSDimitry Andric         if (FuncGrowth / FuncSize > MaxCodeSizeGrowth)
9075f757f3fSDimitry Andric           return false;
9085f757f3fSDimitry Andric         return true;
9095f757f3fSDimitry Andric       };
91081ad6265SDimitry Andric 
911bdd1243dSDimitry Andric       // Discard unprofitable specialisations.
9125f757f3fSDimitry Andric       if (!IsProfitable(B, Score, FuncSize, FunctionGrowth[F]))
913bdd1243dSDimitry Andric         continue;
914bdd1243dSDimitry Andric 
915bdd1243dSDimitry Andric       // Create a new specialisation entry.
9165f757f3fSDimitry Andric       Score += std::max(B.CodeSize, B.Latency);
91706c3fb27SDimitry Andric       auto &Spec = AllSpecs.emplace_back(F, S, Score);
918bdd1243dSDimitry Andric       if (CS.getFunction() != F)
919bdd1243dSDimitry Andric         Spec.CallSites.push_back(&CS);
920bdd1243dSDimitry Andric       const unsigned Index = AllSpecs.size() - 1;
92106c3fb27SDimitry Andric       UniqueSpecs[S] = Index;
922bdd1243dSDimitry Andric       if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted)
923bdd1243dSDimitry Andric         It->second.second = Index + 1;
92481ad6265SDimitry Andric     }
9250eae32dcSDimitry Andric   }
9260eae32dcSDimitry Andric 
92706c3fb27SDimitry Andric   return !UniqueSpecs.empty();
9280eae32dcSDimitry Andric }
9290eae32dcSDimitry Andric 
930bdd1243dSDimitry Andric bool FunctionSpecializer::isCandidateFunction(Function *F) {
93106c3fb27SDimitry Andric   if (F->isDeclaration() || F->arg_empty())
932bdd1243dSDimitry Andric     return false;
9330eae32dcSDimitry Andric 
934bdd1243dSDimitry Andric   if (F->hasFnAttribute(Attribute::NoDuplicate))
935bdd1243dSDimitry Andric     return false;
9360eae32dcSDimitry Andric 
937fe6060f1SDimitry Andric   // Do not specialize the cloned function again.
93806c3fb27SDimitry Andric   if (Specializations.contains(F))
939fe6060f1SDimitry Andric     return false;
940fe6060f1SDimitry Andric 
941fe6060f1SDimitry Andric   // If we're optimizing the function for size, we shouldn't specialize it.
942fe6060f1SDimitry Andric   if (F->hasOptSize() ||
943fe6060f1SDimitry Andric       shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
944fe6060f1SDimitry Andric     return false;
945fe6060f1SDimitry Andric 
946fe6060f1SDimitry Andric   // Exit if the function is not executable. There's no point in specializing
947fe6060f1SDimitry Andric   // a dead function.
948fe6060f1SDimitry Andric   if (!Solver.isBlockExecutable(&F->getEntryBlock()))
949fe6060f1SDimitry Andric     return false;
950fe6060f1SDimitry Andric 
951349cc55cSDimitry Andric   // It wastes time to specialize a function which would get inlined finally.
952349cc55cSDimitry Andric   if (F->hasFnAttribute(Attribute::AlwaysInline))
953349cc55cSDimitry Andric     return false;
954349cc55cSDimitry Andric 
955fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
956fe6060f1SDimitry Andric                     << "\n");
9570eae32dcSDimitry Andric   return true;
958349cc55cSDimitry Andric }
959349cc55cSDimitry Andric 
96006c3fb27SDimitry Andric Function *FunctionSpecializer::createSpecialization(Function *F,
96106c3fb27SDimitry Andric                                                     const SpecSig &S) {
9625f757f3fSDimitry Andric   Function *Clone = cloneCandidateFunction(F, Specializations.size() + 1);
963fe6060f1SDimitry Andric 
96406c3fb27SDimitry Andric   // The original function does not neccessarily have internal linkage, but the
96506c3fb27SDimitry Andric   // clone must.
96606c3fb27SDimitry Andric   Clone->setLinkage(GlobalValue::InternalLinkage);
96706c3fb27SDimitry Andric 
968fe6060f1SDimitry Andric   // Initialize the lattice state of the arguments of the function clone,
969fe6060f1SDimitry Andric   // marking the argument on which we specialized the function constant
970fe6060f1SDimitry Andric   // with the given value.
97106c3fb27SDimitry Andric   Solver.setLatticeValueForSpecializationArguments(Clone, S.Args);
972bdd1243dSDimitry Andric   Solver.markBlockExecutable(&Clone->front());
97306c3fb27SDimitry Andric   Solver.addArgumentTrackedFunction(Clone);
97406c3fb27SDimitry Andric   Solver.addTrackedFunction(Clone);
975bdd1243dSDimitry Andric 
976fe6060f1SDimitry Andric   // Mark all the specialized functions
97706c3fb27SDimitry Andric   Specializations.insert(Clone);
97806c3fb27SDimitry Andric   ++NumSpecsCreated;
979fe6060f1SDimitry Andric 
980bdd1243dSDimitry Andric   return Clone;
981fe6060f1SDimitry Andric }
982fe6060f1SDimitry Andric 
9835f757f3fSDimitry Andric /// Compute the inlining bonus for replacing argument \p A with constant \p C.
9845f757f3fSDimitry Andric /// The below heuristic is only concerned with exposing inlining
9855f757f3fSDimitry Andric /// opportunities via indirect call promotion. If the argument is not a
9865f757f3fSDimitry Andric /// (potentially casted) function pointer, give up.
9875f757f3fSDimitry Andric unsigned FunctionSpecializer::getInliningBonus(Argument *A, Constant *C) {
98881ad6265SDimitry Andric   Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts());
989fe6060f1SDimitry Andric   if (!CalledFunction)
9905f757f3fSDimitry Andric     return 0;
991fe6060f1SDimitry Andric 
992fe6060f1SDimitry Andric   // Get TTI for the called function (used for the inline cost).
993fe6060f1SDimitry Andric   auto &CalleeTTI = (GetTTI)(*CalledFunction);
994fe6060f1SDimitry Andric 
995fe6060f1SDimitry Andric   // Look at all the call sites whose called value is the argument.
996fe6060f1SDimitry Andric   // Specializing the function on the argument would allow these indirect
997fe6060f1SDimitry Andric   // calls to be promoted to direct calls. If the indirect call promotion
998fe6060f1SDimitry Andric   // would likely enable the called function to be inlined, specializing is a
999fe6060f1SDimitry Andric   // good idea.
10005f757f3fSDimitry Andric   int InliningBonus = 0;
1001fe6060f1SDimitry Andric   for (User *U : A->users()) {
1002fe6060f1SDimitry Andric     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
1003fe6060f1SDimitry Andric       continue;
1004fe6060f1SDimitry Andric     auto *CS = cast<CallBase>(U);
1005fe6060f1SDimitry Andric     if (CS->getCalledOperand() != A)
1006fe6060f1SDimitry Andric       continue;
1007bdd1243dSDimitry Andric     if (CS->getFunctionType() != CalledFunction->getFunctionType())
1008bdd1243dSDimitry Andric       continue;
1009fe6060f1SDimitry Andric 
1010fe6060f1SDimitry Andric     // Get the cost of inlining the called function at this call site. Note
1011fe6060f1SDimitry Andric     // that this is only an estimate. The called function may eventually
1012fe6060f1SDimitry Andric     // change in a way that leads to it not being inlined here, even though
1013fe6060f1SDimitry Andric     // inlining looks profitable now. For example, one of its called
1014fe6060f1SDimitry Andric     // functions may be inlined into it, making the called function too large
1015fe6060f1SDimitry Andric     // to be inlined into this call site.
1016fe6060f1SDimitry Andric     //
1017fe6060f1SDimitry Andric     // We apply a boost for performing indirect call promotion by increasing
1018fe6060f1SDimitry Andric     // the default threshold by the threshold for indirect calls.
1019fe6060f1SDimitry Andric     auto Params = getInlineParams();
1020fe6060f1SDimitry Andric     Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
1021fe6060f1SDimitry Andric     InlineCost IC =
1022fe6060f1SDimitry Andric         getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
1023fe6060f1SDimitry Andric 
1024fe6060f1SDimitry Andric     // We clamp the bonus for this call to be between zero and the default
1025fe6060f1SDimitry Andric     // threshold.
1026fe6060f1SDimitry Andric     if (IC.isAlways())
10275f757f3fSDimitry Andric       InliningBonus += Params.DefaultThreshold;
1028fe6060f1SDimitry Andric     else if (IC.isVariable() && IC.getCostDelta() > 0)
10295f757f3fSDimitry Andric       InliningBonus += IC.getCostDelta();
103081ad6265SDimitry Andric 
10315f757f3fSDimitry Andric     LLVM_DEBUG(dbgs() << "FnSpecialization:   Inlining bonus " << InliningBonus
103281ad6265SDimitry Andric                       << " for user " << *U << "\n");
1033fe6060f1SDimitry Andric   }
1034fe6060f1SDimitry Andric 
10355f757f3fSDimitry Andric   return InliningBonus > 0 ? static_cast<unsigned>(InliningBonus) : 0;
1036fe6060f1SDimitry Andric }
1037fe6060f1SDimitry Andric 
1038bdd1243dSDimitry Andric /// Determine if it is possible to specialise the function for constant values
1039bdd1243dSDimitry Andric /// of the formal parameter \p A.
1040bdd1243dSDimitry Andric bool FunctionSpecializer::isArgumentInteresting(Argument *A) {
1041bdd1243dSDimitry Andric   // No point in specialization if the argument is unused.
1042bdd1243dSDimitry Andric   if (A->user_empty())
1043bdd1243dSDimitry Andric     return false;
1044bdd1243dSDimitry Andric 
104506c3fb27SDimitry Andric   Type *Ty = A->getType();
104606c3fb27SDimitry Andric   if (!Ty->isPointerTy() && (!SpecializeLiteralConstant ||
104706c3fb27SDimitry Andric       (!Ty->isIntegerTy() && !Ty->isFloatingPointTy() && !Ty->isStructTy())))
1048fe6060f1SDimitry Andric     return false;
104981ad6265SDimitry Andric 
105081ad6265SDimitry Andric   // SCCP solver does not record an argument that will be constructed on
105181ad6265SDimitry Andric   // stack.
1052bdd1243dSDimitry Andric   if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory())
1053bdd1243dSDimitry Andric     return false;
1054fe6060f1SDimitry Andric 
105506c3fb27SDimitry Andric   // For non-argument-tracked functions every argument is overdefined.
105606c3fb27SDimitry Andric   if (!Solver.isArgumentTrackedFunction(A->getParent()))
105706c3fb27SDimitry Andric     return true;
105806c3fb27SDimitry Andric 
1059bdd1243dSDimitry Andric   // Check the lattice value and decide if we should attemt to specialize,
1060bdd1243dSDimitry Andric   // based on this argument. No point in specialization, if the lattice value
1061bdd1243dSDimitry Andric   // is already a constant.
106206c3fb27SDimitry Andric   bool IsOverdefined = Ty->isStructTy()
106306c3fb27SDimitry Andric     ? any_of(Solver.getStructLatticeValueFor(A), SCCPSolver::isOverdefined)
106406c3fb27SDimitry Andric     : SCCPSolver::isOverdefined(Solver.getLatticeValueFor(A));
106506c3fb27SDimitry Andric 
106606c3fb27SDimitry Andric   LLVM_DEBUG(
106706c3fb27SDimitry Andric     if (IsOverdefined)
106806c3fb27SDimitry Andric       dbgs() << "FnSpecialization: Found interesting parameter "
106906c3fb27SDimitry Andric              << A->getNameOrAsOperand() << "\n";
107006c3fb27SDimitry Andric     else
107106c3fb27SDimitry Andric       dbgs() << "FnSpecialization: Nothing to do, parameter "
107206c3fb27SDimitry Andric              << A->getNameOrAsOperand() << " is already constant\n";
107306c3fb27SDimitry Andric   );
107406c3fb27SDimitry Andric   return IsOverdefined;
1075bdd1243dSDimitry Andric }
1076fe6060f1SDimitry Andric 
107706c3fb27SDimitry Andric /// Check if the value \p V  (an actual argument) is a constant or can only
1078bdd1243dSDimitry Andric /// have a constant value. Return that constant.
1079bdd1243dSDimitry Andric Constant *FunctionSpecializer::getCandidateConstant(Value *V) {
1080349cc55cSDimitry Andric   if (isa<PoisonValue>(V))
1081bdd1243dSDimitry Andric     return nullptr;
1082349cc55cSDimitry Andric 
1083bdd1243dSDimitry Andric   // Select for possible specialisation values that are constants or
1084bdd1243dSDimitry Andric   // are deduced to be constants or constant ranges with a single element.
1085bdd1243dSDimitry Andric   Constant *C = dyn_cast<Constant>(V);
108606c3fb27SDimitry Andric   if (!C)
108706c3fb27SDimitry Andric     C = Solver.getConstantOrNull(V);
108806c3fb27SDimitry Andric 
108906c3fb27SDimitry Andric   // Don't specialize on (anything derived from) the address of a non-constant
109006c3fb27SDimitry Andric   // global variable, unless explicitly enabled.
109106c3fb27SDimitry Andric   if (C && C->getType()->isPointerTy() && !C->isNullValue())
109206c3fb27SDimitry Andric     if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C));
109306c3fb27SDimitry Andric         GV && !(GV->isConstant() || SpecializeOnAddress))
1094bdd1243dSDimitry Andric       return nullptr;
1095fe6060f1SDimitry Andric 
1096bdd1243dSDimitry Andric   return C;
1097bdd1243dSDimitry Andric }
109881ad6265SDimitry Andric 
1099bdd1243dSDimitry Andric void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin,
1100bdd1243dSDimitry Andric                                           const Spec *End) {
1101bdd1243dSDimitry Andric   // Collect the call sites that need updating.
1102bdd1243dSDimitry Andric   SmallVector<CallBase *> ToUpdate;
1103bdd1243dSDimitry Andric   for (User *U : F->users())
1104bdd1243dSDimitry Andric     if (auto *CS = dyn_cast<CallBase>(U);
1105bdd1243dSDimitry Andric         CS && CS->getCalledFunction() == F &&
1106bdd1243dSDimitry Andric         Solver.isBlockExecutable(CS->getParent()))
1107bdd1243dSDimitry Andric       ToUpdate.push_back(CS);
1108bdd1243dSDimitry Andric 
1109bdd1243dSDimitry Andric   unsigned NCallsLeft = ToUpdate.size();
1110bdd1243dSDimitry Andric   for (CallBase *CS : ToUpdate) {
1111bdd1243dSDimitry Andric     bool ShouldDecrementCount = CS->getFunction() == F;
1112bdd1243dSDimitry Andric 
1113bdd1243dSDimitry Andric     // Find the best matching specialisation.
1114bdd1243dSDimitry Andric     const Spec *BestSpec = nullptr;
1115bdd1243dSDimitry Andric     for (const Spec &S : make_range(Begin, End)) {
111606c3fb27SDimitry Andric       if (!S.Clone || (BestSpec && S.Score <= BestSpec->Score))
1117fe6060f1SDimitry Andric         continue;
111881ad6265SDimitry Andric 
1119bdd1243dSDimitry Andric       if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) {
112081ad6265SDimitry Andric             unsigned ArgNo = Arg.Formal->getArgNo();
1121bdd1243dSDimitry Andric             return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual;
1122bdd1243dSDimitry Andric           }))
1123fe6060f1SDimitry Andric         continue;
1124fe6060f1SDimitry Andric 
1125bdd1243dSDimitry Andric       BestSpec = &S;
1126fe6060f1SDimitry Andric     }
1127fe6060f1SDimitry Andric 
1128bdd1243dSDimitry Andric     if (BestSpec) {
1129bdd1243dSDimitry Andric       LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS
1130bdd1243dSDimitry Andric                         << " to call " << BestSpec->Clone->getName() << "\n");
1131bdd1243dSDimitry Andric       CS->setCalledFunction(BestSpec->Clone);
1132bdd1243dSDimitry Andric       ShouldDecrementCount = true;
1133fe6060f1SDimitry Andric     }
1134fe6060f1SDimitry Andric 
1135bdd1243dSDimitry Andric     if (ShouldDecrementCount)
1136bdd1243dSDimitry Andric       --NCallsLeft;
1137fe6060f1SDimitry Andric   }
1138fe6060f1SDimitry Andric 
1139bdd1243dSDimitry Andric   // If the function has been completely specialized, the original function
1140bdd1243dSDimitry Andric   // is no longer needed. Mark it unreachable.
114106c3fb27SDimitry Andric   if (NCallsLeft == 0 && Solver.isArgumentTrackedFunction(F)) {
1142bdd1243dSDimitry Andric     Solver.markFunctionUnreachable(F);
1143bdd1243dSDimitry Andric     FullySpecialized.insert(F);
1144349cc55cSDimitry Andric   }
1145fe6060f1SDimitry Andric }
1146