xref: /llvm-project/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp (revision d1b376fd7bf73bca557f3c174d4c129ed4d45ae5)
1 //===- FunctionSpecialization.cpp - Function Specialization ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This specialises functions with constant parameters. Constant parameters
10 // like function pointers and constant globals are propagated to the callee by
11 // specializing the function. The main benefit of this pass at the moment is
12 // that indirect calls are transformed into direct calls, which provides inline
13 // opportunities that the inliner would not have been able to achieve. That's
14 // why function specialisation is run before the inliner in the optimisation
15 // pipeline; that is by design. Otherwise, we would only benefit from constant
16 // passing, which is a valid use-case too, but hasn't been explored much in
17 // terms of performance uplifts, cost-model and compile-time impact.
18 //
19 // Current limitations:
20 // - It does not yet handle integer ranges. We do support "literal constants",
21 //   but that's off by default under an option.
22 // - The cost-model could be further looked into (it mainly focuses on inlining
23 //   benefits),
24 //
25 // Ideas:
26 // - With a function specialization attribute for arguments, we could have
27 //   a direct way to steer function specialization, avoiding the cost-model,
28 //   and thus control compile-times / code-size.
29 //
30 // Todos:
31 // - Specializing recursive functions relies on running the transformation a
32 //   number of times, which is controlled by option
33 //   `func-specialization-max-iters`. Thus, increasing this value and the
34 //   number of iterations, will linearly increase the number of times recursive
35 //   functions get specialized, see also the discussion in
36 //   https://reviews.llvm.org/D106426 for details. Perhaps there is a
37 //   compile-time friendlier way to control/limit the number of specialisations
38 //   for recursive functions.
39 // - Don't transform the function if function specialization does not trigger;
40 //   the SCCPSolver may make IR changes.
41 //
42 // References:
43 // - 2021 LLVM Dev Mtg “Introducing function specialisation, and can we enable
44 //   it by default?”, https://www.youtube.com/watch?v=zJiCjeXgV5Q
45 //
46 //===----------------------------------------------------------------------===//
47 
48 #include "llvm/Transforms/IPO/FunctionSpecialization.h"
49 #include "llvm/ADT/Statistic.h"
50 #include "llvm/Analysis/CodeMetrics.h"
51 #include "llvm/Analysis/ConstantFolding.h"
52 #include "llvm/Analysis/InlineCost.h"
53 #include "llvm/Analysis/InstructionSimplify.h"
54 #include "llvm/Analysis/TargetTransformInfo.h"
55 #include "llvm/Analysis/ValueLattice.h"
56 #include "llvm/Analysis/ValueLatticeUtils.h"
57 #include "llvm/Analysis/ValueTracking.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/Transforms/Scalar/SCCP.h"
60 #include "llvm/Transforms/Utils/Cloning.h"
61 #include "llvm/Transforms/Utils/SCCPSolver.h"
62 #include "llvm/Transforms/Utils/SizeOpts.h"
63 #include <cmath>
64 
65 using namespace llvm;
66 
67 #define DEBUG_TYPE "function-specialization"
68 
69 STATISTIC(NumSpecsCreated, "Number of specializations created");
70 
71 static cl::opt<bool> ForceSpecialization(
72     "force-specialization", cl::init(false), cl::Hidden, cl::desc(
73     "Force function specialization for every call site with a constant "
74     "argument"));
75 
76 static cl::opt<unsigned> MaxClones(
77     "funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc(
78     "The maximum number of clones allowed for a single function "
79     "specialization"));
80 
81 static cl::opt<unsigned> MaxIncomingPhiValues(
82     "funcspec-max-incoming-phi-values", cl::init(4), cl::Hidden, cl::desc(
83     "The maximum number of incoming values a PHI node can have to be "
84     "considered during the specialization bonus estimation"));
85 
86 static cl::opt<unsigned> MaxBlockPredecessors(
87     "funcspec-max-block-predecessors", cl::init(2), cl::Hidden, cl::desc(
88     "The maximum number of predecessors a basic block can have to be "
89     "considered during the estimation of dead code"));
90 
91 static cl::opt<unsigned> MinFunctionSize(
92     "funcspec-min-function-size", cl::init(300), cl::Hidden, cl::desc(
93     "Don't specialize functions that have less than this number of "
94     "instructions"));
95 
96 static cl::opt<unsigned> MinCodeSizeSavings(
97     "funcspec-min-codesize-savings", cl::init(20), cl::Hidden, cl::desc(
98     "Reject specializations whose codesize savings are less than this"
99     "much percent of the original function size"));
100 
101 static cl::opt<unsigned> MinLatencySavings(
102     "funcspec-min-latency-savings", cl::init(70), cl::Hidden, cl::desc(
103     "Reject specializations whose latency savings are less than this"
104     "much percent of the original function size"));
105 
106 static cl::opt<unsigned> MinInliningBonus(
107     "funcspec-min-inlining-bonus", cl::init(300), cl::Hidden, cl::desc(
108     "Reject specializations whose inlining bonus is less than this"
109     "much percent of the original function size"));
110 
111 static cl::opt<bool> SpecializeOnAddress(
112     "funcspec-on-address", cl::init(false), cl::Hidden, cl::desc(
113     "Enable function specialization on the address of global values"));
114 
115 // Disabled by default as it can significantly increase compilation times.
116 //
117 // https://llvm-compile-time-tracker.com
118 // https://github.com/nikic/llvm-compile-time-tracker
119 static cl::opt<bool> SpecializeLiteralConstant(
120     "funcspec-for-literal-constant", cl::init(false), cl::Hidden, cl::desc(
121     "Enable specialization of functions that take a literal constant as an "
122     "argument"));
123 
124 bool InstCostVisitor::canEliminateSuccessor(BasicBlock *BB, BasicBlock *Succ,
125                                          DenseSet<BasicBlock *> &DeadBlocks) {
126   unsigned I = 0;
127   return all_of(predecessors(Succ),
128     [&I, BB, Succ, &DeadBlocks] (BasicBlock *Pred) {
129     return I++ < MaxBlockPredecessors &&
130       (Pred == BB || Pred == Succ || DeadBlocks.contains(Pred));
131   });
132 }
133 
134 // Estimates the codesize savings due to dead code after constant propagation.
135 // \p WorkList represents the basic blocks of a specialization which will
136 // eventually become dead once we replace instructions that are known to be
137 // constants. The successors of such blocks are added to the list as long as
138 // the \p Solver found they were executable prior to specialization, and only
139 // if all their predecessors are dead.
140 Cost InstCostVisitor::estimateBasicBlocks(
141                           SmallVectorImpl<BasicBlock *> &WorkList) {
142   Cost CodeSize = 0;
143   // Accumulate the instruction cost of each basic block weighted by frequency.
144   while (!WorkList.empty()) {
145     BasicBlock *BB = WorkList.pop_back_val();
146 
147     // These blocks are considered dead as far as the InstCostVisitor
148     // is concerned. They haven't been proven dead yet by the Solver,
149     // but may become if we propagate the specialization arguments.
150     if (!DeadBlocks.insert(BB).second)
151       continue;
152 
153     for (Instruction &I : *BB) {
154       // Disregard SSA copies.
155       if (auto *II = dyn_cast<IntrinsicInst>(&I))
156         if (II->getIntrinsicID() == Intrinsic::ssa_copy)
157           continue;
158       // If it's a known constant we have already accounted for it.
159       if (KnownConstants.contains(&I))
160         continue;
161 
162       Cost C = TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
163 
164       LLVM_DEBUG(dbgs() << "FnSpecialization:     CodeSize " << C
165                         << " for user " << I << "\n");
166       CodeSize += C;
167     }
168 
169     // Keep adding dead successors to the list as long as they are
170     // executable and only reachable from dead blocks.
171     for (BasicBlock *SuccBB : successors(BB))
172       if (isBlockExecutable(SuccBB) &&
173           canEliminateSuccessor(BB, SuccBB, DeadBlocks))
174         WorkList.push_back(SuccBB);
175   }
176   return CodeSize;
177 }
178 
179 static Constant *findConstantFor(Value *V, ConstMap &KnownConstants) {
180   if (auto *C = dyn_cast<Constant>(V))
181     return C;
182   if (auto It = KnownConstants.find(V); It != KnownConstants.end())
183     return It->second;
184   return nullptr;
185 }
186 
187 Bonus InstCostVisitor::getBonusFromPendingPHIs() {
188   Bonus B;
189   while (!PendingPHIs.empty()) {
190     Instruction *Phi = PendingPHIs.pop_back_val();
191     // The pending PHIs could have been proven dead by now.
192     if (isBlockExecutable(Phi->getParent()))
193       B += getUserBonus(Phi);
194   }
195   return B;
196 }
197 
198 /// Compute a bonus for replacing argument \p A with constant \p C.
199 Bonus InstCostVisitor::getSpecializationBonus(Argument *A, Constant *C) {
200   LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: "
201                     << C->getNameOrAsOperand() << "\n");
202   Bonus B;
203   for (auto *U : A->users())
204     if (auto *UI = dyn_cast<Instruction>(U))
205       if (isBlockExecutable(UI->getParent()))
206         B += getUserBonus(UI, A, C);
207 
208   LLVM_DEBUG(dbgs() << "FnSpecialization:   Accumulated bonus {CodeSize = "
209                     << B.CodeSize << ", Latency = " << B.Latency
210                     << "} for argument " << *A << "\n");
211   return B;
212 }
213 
214 Bonus InstCostVisitor::getUserBonus(Instruction *User, Value *Use, Constant *C) {
215   // We have already propagated a constant for this user.
216   if (KnownConstants.contains(User))
217     return {0, 0};
218 
219   // Cache the iterator before visiting.
220   LastVisited = Use ? KnownConstants.insert({Use, C}).first
221                     : KnownConstants.end();
222 
223   Cost CodeSize = 0;
224   if (auto *I = dyn_cast<SwitchInst>(User)) {
225     CodeSize = estimateSwitchInst(*I);
226   } else if (auto *I = dyn_cast<BranchInst>(User)) {
227     CodeSize = estimateBranchInst(*I);
228   } else {
229     C = visit(*User);
230     if (!C)
231       return {0, 0};
232   }
233 
234   // Even though it doesn't make sense to bind switch and branch instructions
235   // with a constant, unlike any other instruction type, it prevents estimating
236   // their bonus multiple times.
237   KnownConstants.insert({User, C});
238 
239   CodeSize += TTI.getInstructionCost(User, TargetTransformInfo::TCK_CodeSize);
240 
241   uint64_t Weight = BFI.getBlockFreq(User->getParent()).getFrequency() /
242                     BFI.getEntryFreq();
243 
244   Cost Latency = Weight *
245       TTI.getInstructionCost(User, TargetTransformInfo::TCK_Latency);
246 
247   LLVM_DEBUG(dbgs() << "FnSpecialization:     {CodeSize = " << CodeSize
248                     << ", Latency = " << Latency << "} for user "
249                     << *User << "\n");
250 
251   Bonus B(CodeSize, Latency);
252   for (auto *U : User->users())
253     if (auto *UI = dyn_cast<Instruction>(U))
254       if (UI != User && isBlockExecutable(UI->getParent()))
255         B += getUserBonus(UI, User, C);
256 
257   return B;
258 }
259 
260 Cost InstCostVisitor::estimateSwitchInst(SwitchInst &I) {
261   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
262 
263   if (I.getCondition() != LastVisited->first)
264     return 0;
265 
266   auto *C = dyn_cast<ConstantInt>(LastVisited->second);
267   if (!C)
268     return 0;
269 
270   BasicBlock *Succ = I.findCaseValue(C)->getCaseSuccessor();
271   // Initialize the worklist with the dead basic blocks. These are the
272   // destination labels which are different from the one corresponding
273   // to \p C. They should be executable and have a unique predecessor.
274   SmallVector<BasicBlock *> WorkList;
275   for (const auto &Case : I.cases()) {
276     BasicBlock *BB = Case.getCaseSuccessor();
277     if (BB != Succ && isBlockExecutable(BB) &&
278         canEliminateSuccessor(I.getParent(), BB, DeadBlocks))
279       WorkList.push_back(BB);
280   }
281 
282   return estimateBasicBlocks(WorkList);
283 }
284 
285 Cost InstCostVisitor::estimateBranchInst(BranchInst &I) {
286   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
287 
288   if (I.getCondition() != LastVisited->first)
289     return 0;
290 
291   BasicBlock *Succ = I.getSuccessor(LastVisited->second->isOneValue());
292   // Initialize the worklist with the dead successor as long as
293   // it is executable and has a unique predecessor.
294   SmallVector<BasicBlock *> WorkList;
295   if (isBlockExecutable(Succ) &&
296       canEliminateSuccessor(I.getParent(), Succ, DeadBlocks))
297     WorkList.push_back(Succ);
298 
299   return estimateBasicBlocks(WorkList);
300 }
301 
302 Constant *InstCostVisitor::visitPHINode(PHINode &I) {
303   if (I.getNumIncomingValues() > MaxIncomingPhiValues)
304     return nullptr;
305 
306   bool Inserted = VisitedPHIs.insert(&I).second;
307   Constant *Const = nullptr;
308 
309   for (unsigned Idx = 0, E = I.getNumIncomingValues(); Idx != E; ++Idx) {
310     Value *V = I.getIncomingValue(Idx);
311     if (auto *Inst = dyn_cast<Instruction>(V))
312       if (Inst == &I || DeadBlocks.contains(I.getIncomingBlock(Idx)))
313         continue;
314     Constant *C = findConstantFor(V, KnownConstants);
315     if (!C) {
316       if (Inserted)
317         PendingPHIs.push_back(&I);
318       return nullptr;
319     }
320     if (!Const)
321       Const = C;
322     else if (C != Const)
323       return nullptr;
324   }
325   return Const;
326 }
327 
328 Constant *InstCostVisitor::visitFreezeInst(FreezeInst &I) {
329   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
330 
331   if (isGuaranteedNotToBeUndefOrPoison(LastVisited->second))
332     return LastVisited->second;
333   return nullptr;
334 }
335 
336 Constant *InstCostVisitor::visitCallBase(CallBase &I) {
337   Function *F = I.getCalledFunction();
338   if (!F || !canConstantFoldCallTo(&I, F))
339     return nullptr;
340 
341   SmallVector<Constant *, 8> Operands;
342   Operands.reserve(I.getNumOperands());
343 
344   for (unsigned Idx = 0, E = I.getNumOperands() - 1; Idx != E; ++Idx) {
345     Value *V = I.getOperand(Idx);
346     Constant *C = findConstantFor(V, KnownConstants);
347     if (!C)
348       return nullptr;
349     Operands.push_back(C);
350   }
351 
352   auto Ops = ArrayRef(Operands.begin(), Operands.end());
353   return ConstantFoldCall(&I, F, Ops);
354 }
355 
356 Constant *InstCostVisitor::visitLoadInst(LoadInst &I) {
357   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
358 
359   if (isa<ConstantPointerNull>(LastVisited->second))
360     return nullptr;
361   return ConstantFoldLoadFromConstPtr(LastVisited->second, I.getType(), DL);
362 }
363 
364 Constant *InstCostVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
365   SmallVector<Constant *, 8> Operands;
366   Operands.reserve(I.getNumOperands());
367 
368   for (unsigned Idx = 0, E = I.getNumOperands(); Idx != E; ++Idx) {
369     Value *V = I.getOperand(Idx);
370     Constant *C = findConstantFor(V, KnownConstants);
371     if (!C)
372       return nullptr;
373     Operands.push_back(C);
374   }
375 
376   auto Ops = ArrayRef(Operands.begin(), Operands.end());
377   return ConstantFoldInstOperands(&I, Ops, DL);
378 }
379 
380 Constant *InstCostVisitor::visitSelectInst(SelectInst &I) {
381   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
382 
383   if (I.getCondition() != LastVisited->first)
384     return nullptr;
385 
386   Value *V = LastVisited->second->isZeroValue() ? I.getFalseValue()
387                                                 : I.getTrueValue();
388   Constant *C = findConstantFor(V, KnownConstants);
389   return C;
390 }
391 
392 Constant *InstCostVisitor::visitCastInst(CastInst &I) {
393   return ConstantFoldCastOperand(I.getOpcode(), LastVisited->second,
394                                  I.getType(), DL);
395 }
396 
397 Constant *InstCostVisitor::visitCmpInst(CmpInst &I) {
398   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
399 
400   bool Swap = I.getOperand(1) == LastVisited->first;
401   Value *V = Swap ? I.getOperand(0) : I.getOperand(1);
402   Constant *Other = findConstantFor(V, KnownConstants);
403   if (!Other)
404     return nullptr;
405 
406   Constant *Const = LastVisited->second;
407   return Swap ?
408         ConstantFoldCompareInstOperands(I.getPredicate(), Other, Const, DL)
409       : ConstantFoldCompareInstOperands(I.getPredicate(), Const, Other, DL);
410 }
411 
412 Constant *InstCostVisitor::visitUnaryOperator(UnaryOperator &I) {
413   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
414 
415   return ConstantFoldUnaryOpOperand(I.getOpcode(), LastVisited->second, DL);
416 }
417 
418 Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) {
419   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
420 
421   bool Swap = I.getOperand(1) == LastVisited->first;
422   Value *V = Swap ? I.getOperand(0) : I.getOperand(1);
423   Constant *Other = findConstantFor(V, KnownConstants);
424   if (!Other)
425     return nullptr;
426 
427   Constant *Const = LastVisited->second;
428   return dyn_cast_or_null<Constant>(Swap ?
429         simplifyBinOp(I.getOpcode(), Other, Const, SimplifyQuery(DL))
430       : simplifyBinOp(I.getOpcode(), Const, Other, SimplifyQuery(DL)));
431 }
432 
433 Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca,
434                                                    CallInst *Call) {
435   Value *StoreValue = nullptr;
436   for (auto *User : Alloca->users()) {
437     // We can't use llvm::isAllocaPromotable() as that would fail because of
438     // the usage in the CallInst, which is what we check here.
439     if (User == Call)
440       continue;
441     if (auto *Bitcast = dyn_cast<BitCastInst>(User)) {
442       if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call)
443         return nullptr;
444       continue;
445     }
446 
447     if (auto *Store = dyn_cast<StoreInst>(User)) {
448       // This is a duplicate store, bail out.
449       if (StoreValue || Store->isVolatile())
450         return nullptr;
451       StoreValue = Store->getValueOperand();
452       continue;
453     }
454     // Bail if there is any other unknown usage.
455     return nullptr;
456   }
457 
458   if (!StoreValue)
459     return nullptr;
460 
461   return getCandidateConstant(StoreValue);
462 }
463 
464 // A constant stack value is an AllocaInst that has a single constant
465 // value stored to it. Return this constant if such an alloca stack value
466 // is a function argument.
467 Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call,
468                                                      Value *Val) {
469   if (!Val)
470     return nullptr;
471   Val = Val->stripPointerCasts();
472   if (auto *ConstVal = dyn_cast<ConstantInt>(Val))
473     return ConstVal;
474   auto *Alloca = dyn_cast<AllocaInst>(Val);
475   if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())
476     return nullptr;
477   return getPromotableAlloca(Alloca, Call);
478 }
479 
480 // To support specializing recursive functions, it is important to propagate
481 // constant arguments because after a first iteration of specialisation, a
482 // reduced example may look like this:
483 //
484 //     define internal void @RecursiveFn(i32* arg1) {
485 //       %temp = alloca i32, align 4
486 //       store i32 2 i32* %temp, align 4
487 //       call void @RecursiveFn.1(i32* nonnull %temp)
488 //       ret void
489 //     }
490 //
491 // Before a next iteration, we need to propagate the constant like so
492 // which allows further specialization in next iterations.
493 //
494 //     @funcspec.arg = internal constant i32 2
495 //
496 //     define internal void @someFunc(i32* arg1) {
497 //       call void @otherFunc(i32* nonnull @funcspec.arg)
498 //       ret void
499 //     }
500 //
501 // See if there are any new constant values for the callers of \p F via
502 // stack variables and promote them to global variables.
503 void FunctionSpecializer::promoteConstantStackValues(Function *F) {
504   for (User *U : F->users()) {
505 
506     auto *Call = dyn_cast<CallInst>(U);
507     if (!Call)
508       continue;
509 
510     if (!Solver.isBlockExecutable(Call->getParent()))
511       continue;
512 
513     for (const Use &U : Call->args()) {
514       unsigned Idx = Call->getArgOperandNo(&U);
515       Value *ArgOp = Call->getArgOperand(Idx);
516       Type *ArgOpType = ArgOp->getType();
517 
518       if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy())
519         continue;
520 
521       auto *ConstVal = getConstantStackValue(Call, ArgOp);
522       if (!ConstVal)
523         continue;
524 
525       Value *GV = new GlobalVariable(M, ConstVal->getType(), true,
526                                      GlobalValue::InternalLinkage, ConstVal,
527                                      "funcspec.arg");
528       if (ArgOpType != ConstVal->getType())
529         GV = ConstantExpr::getBitCast(cast<Constant>(GV), ArgOpType);
530 
531       Call->setArgOperand(Idx, GV);
532     }
533   }
534 }
535 
536 // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics
537 // interfere with the promoteConstantStackValues() optimization.
538 static void removeSSACopy(Function &F) {
539   for (BasicBlock &BB : F) {
540     for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
541       auto *II = dyn_cast<IntrinsicInst>(&Inst);
542       if (!II)
543         continue;
544       if (II->getIntrinsicID() != Intrinsic::ssa_copy)
545         continue;
546       Inst.replaceAllUsesWith(II->getOperand(0));
547       Inst.eraseFromParent();
548     }
549   }
550 }
551 
552 /// Remove any ssa_copy intrinsics that may have been introduced.
553 void FunctionSpecializer::cleanUpSSA() {
554   for (Function *F : Specializations)
555     removeSSACopy(*F);
556 }
557 
558 
559 template <> struct llvm::DenseMapInfo<SpecSig> {
560   static inline SpecSig getEmptyKey() { return {~0U, {}}; }
561 
562   static inline SpecSig getTombstoneKey() { return {~1U, {}}; }
563 
564   static unsigned getHashValue(const SpecSig &S) {
565     return static_cast<unsigned>(hash_value(S));
566   }
567 
568   static bool isEqual(const SpecSig &LHS, const SpecSig &RHS) {
569     return LHS == RHS;
570   }
571 };
572 
573 FunctionSpecializer::~FunctionSpecializer() {
574   LLVM_DEBUG(
575     if (NumSpecsCreated > 0)
576       dbgs() << "FnSpecialization: Created " << NumSpecsCreated
577              << " specializations in module " << M.getName() << "\n");
578   // Eliminate dead code.
579   removeDeadFunctions();
580   cleanUpSSA();
581 }
582 
583 /// Attempt to specialize functions in the module to enable constant
584 /// propagation across function boundaries.
585 ///
586 /// \returns true if at least one function is specialized.
587 bool FunctionSpecializer::run() {
588   // Find possible specializations for each function.
589   SpecMap SM;
590   SmallVector<Spec, 32> AllSpecs;
591   unsigned NumCandidates = 0;
592   for (Function &F : M) {
593     if (!isCandidateFunction(&F))
594       continue;
595 
596     auto [It, Inserted] = FunctionMetrics.try_emplace(&F);
597     CodeMetrics &Metrics = It->second;
598     //Analyze the function.
599     if (Inserted) {
600       SmallPtrSet<const Value *, 32> EphValues;
601       CodeMetrics::collectEphemeralValues(&F, &GetAC(F), EphValues);
602       for (BasicBlock &BB : F)
603         Metrics.analyzeBasicBlock(&BB, GetTTI(F), EphValues);
604     }
605 
606     // If the code metrics reveal that we shouldn't duplicate the function,
607     // or if the code size implies that this function is easy to get inlined,
608     // then we shouldn't specialize it.
609     if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() ||
610         (!ForceSpecialization && !F.hasFnAttribute(Attribute::NoInline) &&
611          Metrics.NumInsts < MinFunctionSize))
612       continue;
613 
614     // TODO: For now only consider recursive functions when running multiple
615     // times. This should change if specialization on literal constants gets
616     // enabled.
617     if (!Inserted && !Metrics.isRecursive && !SpecializeLiteralConstant)
618       continue;
619 
620     int64_t Sz = *Metrics.NumInsts.getValue();
621     assert(Sz > 0 && "CodeSize should be positive");
622     // It is safe to down cast from int64_t, NumInsts is always positive.
623     unsigned FuncSize = static_cast<unsigned>(Sz);
624 
625     LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for "
626                       << F.getName() << " is " << FuncSize << "\n");
627 
628     if (Inserted && Metrics.isRecursive)
629       promoteConstantStackValues(&F);
630 
631     if (!findSpecializations(&F, FuncSize, AllSpecs, SM)) {
632       LLVM_DEBUG(
633           dbgs() << "FnSpecialization: No possible specializations found for "
634                  << F.getName() << "\n");
635       continue;
636     }
637 
638     ++NumCandidates;
639   }
640 
641   if (!NumCandidates) {
642     LLVM_DEBUG(
643         dbgs()
644         << "FnSpecialization: No possible specializations found in module\n");
645     return false;
646   }
647 
648   // Choose the most profitable specialisations, which fit in the module
649   // specialization budget, which is derived from maximum number of
650   // specializations per specialization candidate function.
651   auto CompareScore = [&AllSpecs](unsigned I, unsigned J) {
652     return AllSpecs[I].Score > AllSpecs[J].Score;
653   };
654   const unsigned NSpecs =
655       std::min(NumCandidates * MaxClones, unsigned(AllSpecs.size()));
656   SmallVector<unsigned> BestSpecs(NSpecs + 1);
657   std::iota(BestSpecs.begin(), BestSpecs.begin() + NSpecs, 0);
658   if (AllSpecs.size() > NSpecs) {
659     LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed "
660                       << "the maximum number of clones threshold.\n"
661                       << "FnSpecialization: Specializing the "
662                       << NSpecs
663                       << " most profitable candidates.\n");
664     std::make_heap(BestSpecs.begin(), BestSpecs.begin() + NSpecs, CompareScore);
665     for (unsigned I = NSpecs, N = AllSpecs.size(); I < N; ++I) {
666       BestSpecs[NSpecs] = I;
667       std::push_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
668       std::pop_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
669     }
670   }
671 
672   LLVM_DEBUG(dbgs() << "FnSpecialization: List of specializations \n";
673              for (unsigned I = 0; I < NSpecs; ++I) {
674                const Spec &S = AllSpecs[BestSpecs[I]];
675                dbgs() << "FnSpecialization: Function " << S.F->getName()
676                       << " , score " << S.Score << "\n";
677                for (const ArgInfo &Arg : S.Sig.Args)
678                  dbgs() << "FnSpecialization:   FormalArg = "
679                         << Arg.Formal->getNameOrAsOperand()
680                         << ", ActualArg = " << Arg.Actual->getNameOrAsOperand()
681                         << "\n";
682              });
683 
684   // Create the chosen specializations.
685   SmallPtrSet<Function *, 8> OriginalFuncs;
686   SmallVector<Function *> Clones;
687   for (unsigned I = 0; I < NSpecs; ++I) {
688     Spec &S = AllSpecs[BestSpecs[I]];
689     S.Clone = createSpecialization(S.F, S.Sig);
690 
691     // Update the known call sites to call the clone.
692     for (CallBase *Call : S.CallSites) {
693       LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call
694                         << " to call " << S.Clone->getName() << "\n");
695       Call->setCalledFunction(S.Clone);
696     }
697 
698     Clones.push_back(S.Clone);
699     OriginalFuncs.insert(S.F);
700   }
701 
702   Solver.solveWhileResolvedUndefsIn(Clones);
703 
704   // Update the rest of the call sites - these are the recursive calls, calls
705   // to discarded specialisations and calls that may match a specialisation
706   // after the solver runs.
707   for (Function *F : OriginalFuncs) {
708     auto [Begin, End] = SM[F];
709     updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End);
710   }
711 
712   for (Function *F : Clones) {
713     if (F->getReturnType()->isVoidTy())
714       continue;
715     if (F->getReturnType()->isStructTy()) {
716       auto *STy = cast<StructType>(F->getReturnType());
717       if (!Solver.isStructLatticeConstant(F, STy))
718         continue;
719     } else {
720       auto It = Solver.getTrackedRetVals().find(F);
721       assert(It != Solver.getTrackedRetVals().end() &&
722              "Return value ought to be tracked");
723       if (SCCPSolver::isOverdefined(It->second))
724         continue;
725     }
726     for (User *U : F->users()) {
727       if (auto *CS = dyn_cast<CallBase>(U)) {
728         //The user instruction does not call our function.
729         if (CS->getCalledFunction() != F)
730           continue;
731         Solver.resetLatticeValueFor(CS);
732       }
733     }
734   }
735 
736   // Rerun the solver to notify the users of the modified callsites.
737   Solver.solveWhileResolvedUndefs();
738 
739   for (Function *F : OriginalFuncs)
740     if (FunctionMetrics[F].isRecursive)
741       promoteConstantStackValues(F);
742 
743   return true;
744 }
745 
746 void FunctionSpecializer::removeDeadFunctions() {
747   for (Function *F : FullySpecialized) {
748     LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function "
749                       << F->getName() << "\n");
750     if (FAM)
751       FAM->clear(*F, F->getName());
752     F->eraseFromParent();
753   }
754   FullySpecialized.clear();
755 }
756 
757 /// Clone the function \p F and remove the ssa_copy intrinsics added by
758 /// the SCCPSolver in the cloned version.
759 static Function *cloneCandidateFunction(Function *F) {
760   ValueToValueMapTy Mappings;
761   Function *Clone = CloneFunction(F, Mappings);
762   removeSSACopy(*Clone);
763   return Clone;
764 }
765 
766 bool FunctionSpecializer::findSpecializations(Function *F, unsigned FuncSize,
767                                               SmallVectorImpl<Spec> &AllSpecs,
768                                               SpecMap &SM) {
769   // A mapping from a specialisation signature to the index of the respective
770   // entry in the all specialisation array. Used to ensure uniqueness of
771   // specialisations.
772   DenseMap<SpecSig, unsigned> UniqueSpecs;
773 
774   // Get a list of interesting arguments.
775   SmallVector<Argument *> Args;
776   for (Argument &Arg : F->args())
777     if (isArgumentInteresting(&Arg))
778       Args.push_back(&Arg);
779 
780   if (Args.empty())
781     return false;
782 
783   for (User *U : F->users()) {
784     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
785       continue;
786     auto &CS = *cast<CallBase>(U);
787 
788     // The user instruction does not call our function.
789     if (CS.getCalledFunction() != F)
790       continue;
791 
792     // If the call site has attribute minsize set, that callsite won't be
793     // specialized.
794     if (CS.hasFnAttr(Attribute::MinSize))
795       continue;
796 
797     // If the parent of the call site will never be executed, we don't need
798     // to worry about the passed value.
799     if (!Solver.isBlockExecutable(CS.getParent()))
800       continue;
801 
802     // Examine arguments and create a specialisation candidate from the
803     // constant operands of this call site.
804     SpecSig S;
805     for (Argument *A : Args) {
806       Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo()));
807       if (!C)
808         continue;
809       LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument "
810                         << A->getName() << " : " << C->getNameOrAsOperand()
811                         << "\n");
812       S.Args.push_back({A, C});
813     }
814 
815     if (S.Args.empty())
816       continue;
817 
818     // Check if we have encountered the same specialisation already.
819     if (auto It = UniqueSpecs.find(S); It != UniqueSpecs.end()) {
820       // Existing specialisation. Add the call to the list to rewrite, unless
821       // it's a recursive call. A specialisation, generated because of a
822       // recursive call may end up as not the best specialisation for all
823       // the cloned instances of this call, which result from specialising
824       // functions. Hence we don't rewrite the call directly, but match it with
825       // the best specialisation once all specialisations are known.
826       if (CS.getFunction() == F)
827         continue;
828       const unsigned Index = It->second;
829       AllSpecs[Index].CallSites.push_back(&CS);
830     } else {
831       // Calculate the specialisation gain.
832       Bonus B;
833       unsigned Score = 0;
834       InstCostVisitor Visitor = getInstCostVisitorFor(F);
835       for (ArgInfo &A : S.Args) {
836         B += Visitor.getSpecializationBonus(A.Formal, A.Actual);
837         Score += getInliningBonus(A.Formal, A.Actual);
838       }
839       B += Visitor.getBonusFromPendingPHIs();
840 
841 
842       LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization bonus {CodeSize = "
843                         << B.CodeSize << ", Latency = " << B.Latency
844                         << ", Inlining = " << Score << "}\n");
845 
846       auto IsProfitable = [&FuncSize](Bonus &B, unsigned Score) -> bool {
847         // No check required.
848         if (ForceSpecialization)
849           return true;
850         // Minimum inlining bonus.
851         if (Score > MinInliningBonus * FuncSize / 100)
852           return true;
853         // Minimum codesize savings.
854         if (B.CodeSize < MinCodeSizeSavings * FuncSize / 100)
855           return false;
856         // Minimum latency savings.
857         if (B.Latency < MinLatencySavings * FuncSize / 100)
858           return false;
859         return true;
860       };
861 
862       // Discard unprofitable specialisations.
863       if (!IsProfitable(B, Score))
864         continue;
865 
866       // Create a new specialisation entry.
867       Score += std::max(B.CodeSize, B.Latency);
868       auto &Spec = AllSpecs.emplace_back(F, S, Score);
869       if (CS.getFunction() != F)
870         Spec.CallSites.push_back(&CS);
871       const unsigned Index = AllSpecs.size() - 1;
872       UniqueSpecs[S] = Index;
873       if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted)
874         It->second.second = Index + 1;
875     }
876   }
877 
878   return !UniqueSpecs.empty();
879 }
880 
881 bool FunctionSpecializer::isCandidateFunction(Function *F) {
882   if (F->isDeclaration() || F->arg_empty())
883     return false;
884 
885   if (F->hasFnAttribute(Attribute::NoDuplicate))
886     return false;
887 
888   // Do not specialize the cloned function again.
889   if (Specializations.contains(F))
890     return false;
891 
892   // If we're optimizing the function for size, we shouldn't specialize it.
893   if (F->hasOptSize() ||
894       shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
895     return false;
896 
897   // Exit if the function is not executable. There's no point in specializing
898   // a dead function.
899   if (!Solver.isBlockExecutable(&F->getEntryBlock()))
900     return false;
901 
902   // It wastes time to specialize a function which would get inlined finally.
903   if (F->hasFnAttribute(Attribute::AlwaysInline))
904     return false;
905 
906   LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
907                     << "\n");
908   return true;
909 }
910 
911 Function *FunctionSpecializer::createSpecialization(Function *F,
912                                                     const SpecSig &S) {
913   Function *Clone = cloneCandidateFunction(F);
914 
915   // The original function does not neccessarily have internal linkage, but the
916   // clone must.
917   Clone->setLinkage(GlobalValue::InternalLinkage);
918 
919   // Initialize the lattice state of the arguments of the function clone,
920   // marking the argument on which we specialized the function constant
921   // with the given value.
922   Solver.setLatticeValueForSpecializationArguments(Clone, S.Args);
923   Solver.markBlockExecutable(&Clone->front());
924   Solver.addArgumentTrackedFunction(Clone);
925   Solver.addTrackedFunction(Clone);
926 
927   // Mark all the specialized functions
928   Specializations.insert(Clone);
929   ++NumSpecsCreated;
930 
931   return Clone;
932 }
933 
934 /// Compute the inlining bonus for replacing argument \p A with constant \p C.
935 /// The below heuristic is only concerned with exposing inlining
936 /// opportunities via indirect call promotion. If the argument is not a
937 /// (potentially casted) function pointer, give up.
938 unsigned FunctionSpecializer::getInliningBonus(Argument *A, Constant *C) {
939   Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts());
940   if (!CalledFunction)
941     return 0;
942 
943   // Get TTI for the called function (used for the inline cost).
944   auto &CalleeTTI = (GetTTI)(*CalledFunction);
945 
946   // Look at all the call sites whose called value is the argument.
947   // Specializing the function on the argument would allow these indirect
948   // calls to be promoted to direct calls. If the indirect call promotion
949   // would likely enable the called function to be inlined, specializing is a
950   // good idea.
951   int InliningBonus = 0;
952   for (User *U : A->users()) {
953     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
954       continue;
955     auto *CS = cast<CallBase>(U);
956     if (CS->getCalledOperand() != A)
957       continue;
958     if (CS->getFunctionType() != CalledFunction->getFunctionType())
959       continue;
960 
961     // Get the cost of inlining the called function at this call site. Note
962     // that this is only an estimate. The called function may eventually
963     // change in a way that leads to it not being inlined here, even though
964     // inlining looks profitable now. For example, one of its called
965     // functions may be inlined into it, making the called function too large
966     // to be inlined into this call site.
967     //
968     // We apply a boost for performing indirect call promotion by increasing
969     // the default threshold by the threshold for indirect calls.
970     auto Params = getInlineParams();
971     Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
972     InlineCost IC =
973         getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
974 
975     // We clamp the bonus for this call to be between zero and the default
976     // threshold.
977     if (IC.isAlways())
978       InliningBonus += Params.DefaultThreshold;
979     else if (IC.isVariable() && IC.getCostDelta() > 0)
980       InliningBonus += IC.getCostDelta();
981 
982     LLVM_DEBUG(dbgs() << "FnSpecialization:   Inlining bonus " << InliningBonus
983                       << " for user " << *U << "\n");
984   }
985 
986   return InliningBonus > 0 ? static_cast<unsigned>(InliningBonus) : 0;
987 }
988 
989 /// Determine if it is possible to specialise the function for constant values
990 /// of the formal parameter \p A.
991 bool FunctionSpecializer::isArgumentInteresting(Argument *A) {
992   // No point in specialization if the argument is unused.
993   if (A->user_empty())
994     return false;
995 
996   Type *Ty = A->getType();
997   if (!Ty->isPointerTy() && (!SpecializeLiteralConstant ||
998       (!Ty->isIntegerTy() && !Ty->isFloatingPointTy() && !Ty->isStructTy())))
999     return false;
1000 
1001   // SCCP solver does not record an argument that will be constructed on
1002   // stack.
1003   if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory())
1004     return false;
1005 
1006   // For non-argument-tracked functions every argument is overdefined.
1007   if (!Solver.isArgumentTrackedFunction(A->getParent()))
1008     return true;
1009 
1010   // Check the lattice value and decide if we should attemt to specialize,
1011   // based on this argument. No point in specialization, if the lattice value
1012   // is already a constant.
1013   bool IsOverdefined = Ty->isStructTy()
1014     ? any_of(Solver.getStructLatticeValueFor(A), SCCPSolver::isOverdefined)
1015     : SCCPSolver::isOverdefined(Solver.getLatticeValueFor(A));
1016 
1017   LLVM_DEBUG(
1018     if (IsOverdefined)
1019       dbgs() << "FnSpecialization: Found interesting parameter "
1020              << A->getNameOrAsOperand() << "\n";
1021     else
1022       dbgs() << "FnSpecialization: Nothing to do, parameter "
1023              << A->getNameOrAsOperand() << " is already constant\n";
1024   );
1025   return IsOverdefined;
1026 }
1027 
1028 /// Check if the value \p V  (an actual argument) is a constant or can only
1029 /// have a constant value. Return that constant.
1030 Constant *FunctionSpecializer::getCandidateConstant(Value *V) {
1031   if (isa<PoisonValue>(V))
1032     return nullptr;
1033 
1034   // Select for possible specialisation values that are constants or
1035   // are deduced to be constants or constant ranges with a single element.
1036   Constant *C = dyn_cast<Constant>(V);
1037   if (!C)
1038     C = Solver.getConstantOrNull(V);
1039 
1040   // Don't specialize on (anything derived from) the address of a non-constant
1041   // global variable, unless explicitly enabled.
1042   if (C && C->getType()->isPointerTy() && !C->isNullValue())
1043     if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C));
1044         GV && !(GV->isConstant() || SpecializeOnAddress))
1045       return nullptr;
1046 
1047   return C;
1048 }
1049 
1050 void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin,
1051                                           const Spec *End) {
1052   // Collect the call sites that need updating.
1053   SmallVector<CallBase *> ToUpdate;
1054   for (User *U : F->users())
1055     if (auto *CS = dyn_cast<CallBase>(U);
1056         CS && CS->getCalledFunction() == F &&
1057         Solver.isBlockExecutable(CS->getParent()))
1058       ToUpdate.push_back(CS);
1059 
1060   unsigned NCallsLeft = ToUpdate.size();
1061   for (CallBase *CS : ToUpdate) {
1062     bool ShouldDecrementCount = CS->getFunction() == F;
1063 
1064     // Find the best matching specialisation.
1065     const Spec *BestSpec = nullptr;
1066     for (const Spec &S : make_range(Begin, End)) {
1067       if (!S.Clone || (BestSpec && S.Score <= BestSpec->Score))
1068         continue;
1069 
1070       if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) {
1071             unsigned ArgNo = Arg.Formal->getArgNo();
1072             return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual;
1073           }))
1074         continue;
1075 
1076       BestSpec = &S;
1077     }
1078 
1079     if (BestSpec) {
1080       LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS
1081                         << " to call " << BestSpec->Clone->getName() << "\n");
1082       CS->setCalledFunction(BestSpec->Clone);
1083       ShouldDecrementCount = true;
1084     }
1085 
1086     if (ShouldDecrementCount)
1087       --NCallsLeft;
1088   }
1089 
1090   // If the function has been completely specialized, the original function
1091   // is no longer needed. Mark it unreachable.
1092   if (NCallsLeft == 0 && Solver.isArgumentTrackedFunction(F)) {
1093     Solver.markFunctionUnreachable(F);
1094     FullySpecialized.insert(F);
1095   }
1096 }
1097