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