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