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 (e.g. functions,
10 // globals). Constant parameters like function pointers and constant globals
11 // are propagated to the callee by specializing the function.
12 //
13 // Current limitations:
14 // - It does not yet handle integer ranges.
15 // - Only 1 argument per function is specialised,
16 // - The cost-model could be further looked into,
17 // - We are not yet caching analysis results.
18 //
19 // Ideas:
20 // - With a function specialization attribute for arguments, we could have
21 //   a direct way to steer function specialization, avoiding the cost-model,
22 //   and thus control compile-times / code-size.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AssumptionCache.h"
28 #include "llvm/Analysis/CodeMetrics.h"
29 #include "llvm/Analysis/DomTreeUpdater.h"
30 #include "llvm/Analysis/InlineCost.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/TargetLibraryInfo.h"
33 #include "llvm/Analysis/TargetTransformInfo.h"
34 #include "llvm/Transforms/Scalar/SCCP.h"
35 #include "llvm/Transforms/Utils/Cloning.h"
36 #include "llvm/Transforms/Utils/SizeOpts.h"
37 #include <cmath>
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "function-specialization"
42 
43 STATISTIC(NumFuncSpecialized, "Number of functions specialized");
44 
45 static cl::opt<bool> ForceFunctionSpecialization(
46     "force-function-specialization", cl::init(false), cl::Hidden,
47     cl::desc("Force function specialization for every call site with a "
48              "constant argument"));
49 
50 static cl::opt<unsigned> FuncSpecializationMaxIters(
51     "func-specialization-max-iters", cl::Hidden,
52     cl::desc("The maximum number of iterations function specialization is run"),
53     cl::init(1));
54 
55 static cl::opt<unsigned> MaxConstantsThreshold(
56     "func-specialization-max-constants", cl::Hidden,
57     cl::desc("The maximum number of clones allowed for a single function "
58              "specialization"),
59     cl::init(3));
60 
61 static cl::opt<unsigned>
62     AvgLoopIterationCount("func-specialization-avg-iters-cost", cl::Hidden,
63                           cl::desc("Average loop iteration count cost"),
64                           cl::init(10));
65 
66 static cl::opt<bool> EnableSpecializationForLiteralConstant(
67     "function-specialization-for-literal-constant", cl::init(false), cl::Hidden,
68     cl::desc("Make function specialization available for literal constant."));
69 
70 // Helper to check if \p LV is either a constant or a constant
71 // range with a single element. This should cover exactly the same cases as the
72 // old ValueLatticeElement::isConstant() and is intended to be used in the
73 // transition to ValueLatticeElement.
74 static bool isConstant(const ValueLatticeElement &LV) {
75   return LV.isConstant() ||
76          (LV.isConstantRange() && LV.getConstantRange().isSingleElement());
77 }
78 
79 // Helper to check if \p LV is either overdefined or a constant int.
80 static bool isOverdefined(const ValueLatticeElement &LV) {
81   return !LV.isUnknownOrUndef() && !isConstant(LV);
82 }
83 
84 static Constant *getPromotableAlloca(AllocaInst *Alloca, CallInst *Call) {
85   Value *StoreValue = nullptr;
86   for (auto *User : Alloca->users()) {
87     // We can't use llvm::isAllocaPromotable() as that would fail because of
88     // the usage in the CallInst, which is what we check here.
89     if (User == Call)
90       continue;
91     if (auto *Bitcast = dyn_cast<BitCastInst>(User)) {
92       if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call)
93         return nullptr;
94       continue;
95     }
96 
97     if (auto *Store = dyn_cast<StoreInst>(User)) {
98       // This is a duplicate store, bail out.
99       if (StoreValue || Store->isVolatile())
100         return nullptr;
101       StoreValue = Store->getValueOperand();
102       continue;
103     }
104     // Bail if there is any other unknown usage.
105     return nullptr;
106   }
107   return dyn_cast_or_null<Constant>(StoreValue);
108 }
109 
110 // A constant stack value is an AllocaInst that has a single constant
111 // value stored to it. Return this constant if such an alloca stack value
112 // is a function argument.
113 static Constant *getConstantStackValue(CallInst *Call, Value *Val,
114                                        SCCPSolver &Solver) {
115   if (!Val)
116     return nullptr;
117   Val = Val->stripPointerCasts();
118   if (auto *ConstVal = dyn_cast<ConstantInt>(Val))
119     return ConstVal;
120   auto *Alloca = dyn_cast<AllocaInst>(Val);
121   if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())
122     return nullptr;
123   return getPromotableAlloca(Alloca, Call);
124 }
125 
126 // To support specializing recursive functions, it is important to propagate
127 // constant arguments because after a first iteration of specialisation, a
128 // reduced example may look like this:
129 //
130 //     define internal void @RecursiveFn(i32* arg1) {
131 //       %temp = alloca i32, align 4
132 //       store i32 2 i32* %temp, align 4
133 //       call void @RecursiveFn.1(i32* nonnull %temp)
134 //       ret void
135 //     }
136 //
137 // Before a next iteration, we need to propagate the constant like so
138 // which allows further specialization in next iterations.
139 //
140 //     @funcspec.arg = internal constant i32 2
141 //
142 //     define internal void @someFunc(i32* arg1) {
143 //       call void @otherFunc(i32* nonnull @funcspec.arg)
144 //       ret void
145 //     }
146 //
147 static void constantArgPropagation(SmallVectorImpl<Function *> &WorkList,
148                                    Module &M, SCCPSolver &Solver) {
149   // Iterate over the argument tracked functions see if there
150   // are any new constant values for the call instruction via
151   // stack variables.
152   for (auto *F : WorkList) {
153     // TODO: Generalize for any read only arguments.
154     if (F->arg_size() != 1)
155       continue;
156 
157     auto &Arg = *F->arg_begin();
158     if (!Arg.onlyReadsMemory() || !Arg.getType()->isPointerTy())
159       continue;
160 
161     for (auto *User : F->users()) {
162       auto *Call = dyn_cast<CallInst>(User);
163       if (!Call)
164         break;
165       auto *ArgOp = Call->getArgOperand(0);
166       auto *ArgOpType = ArgOp->getType();
167       auto *ConstVal = getConstantStackValue(Call, ArgOp, Solver);
168       if (!ConstVal)
169         break;
170 
171       Value *GV = new GlobalVariable(M, ConstVal->getType(), true,
172                                      GlobalValue::InternalLinkage, ConstVal,
173                                      "funcspec.arg");
174 
175       if (ArgOpType != ConstVal->getType())
176         GV = ConstantExpr::getBitCast(cast<Constant>(GV), ArgOp->getType());
177 
178       Call->setArgOperand(0, GV);
179 
180       // Add the changed CallInst to Solver Worklist
181       Solver.visitCall(*Call);
182     }
183   }
184 }
185 
186 // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics
187 // interfere with the constantArgPropagation optimization.
188 static void removeSSACopy(Function &F) {
189   for (BasicBlock &BB : F) {
190     for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
191       Instruction *Inst = &*BI++;
192       auto *II = dyn_cast<IntrinsicInst>(Inst);
193       if (!II)
194         continue;
195       if (II->getIntrinsicID() != Intrinsic::ssa_copy)
196         continue;
197       Inst->replaceAllUsesWith(II->getOperand(0));
198       Inst->eraseFromParent();
199     }
200   }
201 }
202 
203 static void removeSSACopy(Module &M) {
204   for (Function &F : M)
205     removeSSACopy(F);
206 }
207 
208 class FunctionSpecializer {
209 
210   /// The IPSCCP Solver.
211   SCCPSolver &Solver;
212 
213   /// Analyses used to help determine if a function should be specialized.
214   std::function<AssumptionCache &(Function &)> GetAC;
215   std::function<TargetTransformInfo &(Function &)> GetTTI;
216   std::function<TargetLibraryInfo &(Function &)> GetTLI;
217 
218   SmallPtrSet<Function *, 2> SpecializedFuncs;
219 
220 public:
221   FunctionSpecializer(SCCPSolver &Solver,
222                       std::function<AssumptionCache &(Function &)> GetAC,
223                       std::function<TargetTransformInfo &(Function &)> GetTTI,
224                       std::function<TargetLibraryInfo &(Function &)> GetTLI)
225       : Solver(Solver), GetAC(GetAC), GetTTI(GetTTI), GetTLI(GetTLI) {}
226 
227   /// Attempt to specialize functions in the module to enable constant
228   /// propagation across function boundaries.
229   ///
230   /// \returns true if at least one function is specialized.
231   bool
232   specializeFunctions(SmallVectorImpl<Function *> &FuncDecls,
233                       SmallVectorImpl<Function *> &CurrentSpecializations) {
234 
235     // Attempt to specialize the argument-tracked functions.
236     bool Changed = false;
237     for (auto *F : FuncDecls) {
238       if (specializeFunction(F, CurrentSpecializations)) {
239         Changed = true;
240         LLVM_DEBUG(dbgs() << "FnSpecialization: Can specialize this func.\n");
241       } else {
242         LLVM_DEBUG(
243             dbgs() << "FnSpecialization: Cannot specialize this func.\n");
244       }
245     }
246 
247     for (auto *SpecializedFunc : CurrentSpecializations) {
248       SpecializedFuncs.insert(SpecializedFunc);
249 
250       // Initialize the state of the newly created functions, marking them
251       // argument-tracked and executable.
252       if (SpecializedFunc->hasExactDefinition() &&
253           !SpecializedFunc->hasFnAttribute(Attribute::Naked))
254         Solver.addTrackedFunction(SpecializedFunc);
255       Solver.addArgumentTrackedFunction(SpecializedFunc);
256       FuncDecls.push_back(SpecializedFunc);
257       Solver.markBlockExecutable(&SpecializedFunc->front());
258 
259       // Replace the function arguments for the specialized functions.
260       for (Argument &Arg : SpecializedFunc->args())
261         if (!Arg.use_empty() && tryToReplaceWithConstant(&Arg))
262           LLVM_DEBUG(dbgs() << "FnSpecialization: Replaced constant argument: "
263                             << Arg.getName() << "\n");
264     }
265 
266     NumFuncSpecialized += NbFunctionsSpecialized;
267     return Changed;
268   }
269 
270   bool tryToReplaceWithConstant(Value *V) {
271     if (!V->getType()->isSingleValueType() || isa<CallBase>(V) ||
272         V->user_empty())
273       return false;
274 
275     const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
276     if (isOverdefined(IV))
277       return false;
278     auto *Const =
279         isConstant(IV) ? Solver.getConstant(IV) : UndefValue::get(V->getType());
280     V->replaceAllUsesWith(Const);
281 
282     for (auto *U : Const->users())
283       if (auto *I = dyn_cast<Instruction>(U))
284         if (Solver.isBlockExecutable(I->getParent()))
285           Solver.visit(I);
286 
287     // Remove the instruction from Block and Solver.
288     if (auto *I = dyn_cast<Instruction>(V)) {
289       if (I->isSafeToRemove()) {
290         I->eraseFromParent();
291         Solver.removeLatticeValueFor(I);
292       }
293     }
294     return true;
295   }
296 
297 private:
298   // The number of functions specialised, used for collecting statistics and
299   // also in the cost model.
300   unsigned NbFunctionsSpecialized = 0;
301 
302   /// Clone the function \p F and remove the ssa_copy intrinsics added by
303   /// the SCCPSolver in the cloned version.
304   Function *cloneCandidateFunction(Function *F) {
305     ValueToValueMapTy EmptyMap;
306     Function *Clone = CloneFunction(F, EmptyMap);
307     removeSSACopy(*Clone);
308     return Clone;
309   }
310 
311   /// This function decides whether to specialize function \p F based on the
312   /// known constant values its arguments can take on. Specialization is
313   /// performed on the first interesting argument. Specializations based on
314   /// additional arguments will be evaluated on following iterations of the
315   /// main IPSCCP solve loop. \returns true if the function is specialized and
316   /// false otherwise.
317   bool specializeFunction(Function *F,
318                           SmallVectorImpl<Function *> &Specializations) {
319 
320     // Do not specialize the cloned function again.
321     if (SpecializedFuncs.contains(F)) {
322       return false;
323     }
324 
325     // If we're optimizing the function for size, we shouldn't specialize it.
326     if (F->hasOptSize() ||
327         shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
328       return false;
329 
330     // Exit if the function is not executable. There's no point in specializing
331     // a dead function.
332     if (!Solver.isBlockExecutable(&F->getEntryBlock()))
333       return false;
334 
335     LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
336                       << "\n");
337     // Determine if we should specialize the function based on the values the
338     // argument can take on. If specialization is not profitable, we continue
339     // on to the next argument.
340     for (Argument &A : F->args()) {
341       LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing arg: " << A.getName()
342                         << "\n");
343       // True if this will be a partial specialization. We will need to keep
344       // the original function around in addition to the added specializations.
345       bool IsPartial = true;
346 
347       // Determine if this argument is interesting. If we know the argument can
348       // take on any constant values, they are collected in Constants. If the
349       // argument can only ever equal a constant value in Constants, the
350       // function will be completely specialized, and the IsPartial flag will
351       // be set to false by isArgumentInteresting (that function only adds
352       // values to the Constants list that are deemed profitable).
353       SmallVector<Constant *, 4> Constants;
354       if (!isArgumentInteresting(&A, Constants, IsPartial)) {
355         LLVM_DEBUG(dbgs() << "FnSpecialization: Argument is not interesting\n");
356         continue;
357       }
358 
359       assert(!Constants.empty() && "No constants on which to specialize");
360       LLVM_DEBUG(dbgs() << "FnSpecialization: Argument is interesting!\n"
361                         << "FnSpecialization: Specializing '" << F->getName()
362                         << "' on argument: " << A << "\n"
363                         << "FnSpecialization: Constants are:\n\n";
364                  for (unsigned I = 0; I < Constants.size(); ++I) dbgs()
365                  << *Constants[I] << "\n";
366                  dbgs() << "FnSpecialization: End of constants\n\n");
367 
368       // Create a version of the function in which the argument is marked
369       // constant with the given value.
370       for (auto *C : Constants) {
371         // Clone the function. We leave the ValueToValueMap empty to allow
372         // IPSCCP to propagate the constant arguments.
373         Function *Clone = cloneCandidateFunction(F);
374         Argument *ClonedArg = Clone->arg_begin() + A.getArgNo();
375 
376         // Rewrite calls to the function so that they call the clone instead.
377         rewriteCallSites(F, Clone, *ClonedArg, C);
378 
379         // Initialize the lattice state of the arguments of the function clone,
380         // marking the argument on which we specialized the function constant
381         // with the given value.
382         Solver.markArgInFuncSpecialization(F, ClonedArg, C);
383 
384         // Mark all the specialized functions
385         Specializations.push_back(Clone);
386         NbFunctionsSpecialized++;
387       }
388 
389       // If the function has been completely specialized, the original function
390       // is no longer needed. Mark it unreachable.
391       if (!IsPartial)
392         Solver.markFunctionUnreachable(F);
393 
394       // FIXME: Only one argument per function.
395       return true;
396     }
397 
398     return false;
399   }
400 
401   /// Compute the cost of specializing function \p F.
402   InstructionCost getSpecializationCost(Function *F) {
403     // Compute the code metrics for the function.
404     SmallPtrSet<const Value *, 32> EphValues;
405     CodeMetrics::collectEphemeralValues(F, &(GetAC)(*F), EphValues);
406     CodeMetrics Metrics;
407     for (BasicBlock &BB : *F)
408       Metrics.analyzeBasicBlock(&BB, (GetTTI)(*F), EphValues);
409 
410     // If the code metrics reveal that we shouldn't duplicate the function, we
411     // shouldn't specialize it. Set the specialization cost to Invalid.
412     if (Metrics.notDuplicatable) {
413       InstructionCost C{};
414       C.setInvalid();
415       return C;
416     }
417 
418     // Otherwise, set the specialization cost to be the cost of all the
419     // instructions in the function and penalty for specializing more functions.
420     unsigned Penalty = NbFunctionsSpecialized + 1;
421     return Metrics.NumInsts * InlineConstants::InstrCost * Penalty;
422   }
423 
424   InstructionCost getUserBonus(User *U, llvm::TargetTransformInfo &TTI,
425                                LoopInfo &LI) {
426     auto *I = dyn_cast_or_null<Instruction>(U);
427     // If not an instruction we do not know how to evaluate.
428     // Keep minimum possible cost for now so that it doesnt affect
429     // specialization.
430     if (!I)
431       return std::numeric_limits<unsigned>::min();
432 
433     auto Cost = TTI.getUserCost(U, TargetTransformInfo::TCK_SizeAndLatency);
434 
435     // Traverse recursively if there are more uses.
436     // TODO: Any other instructions to be added here?
437     if (I->mayReadFromMemory() || I->isCast())
438       for (auto *User : I->users())
439         Cost += getUserBonus(User, TTI, LI);
440 
441     // Increase the cost if it is inside the loop.
442     auto LoopDepth = LI.getLoopDepth(I->getParent());
443     Cost *= std::pow((double)AvgLoopIterationCount, LoopDepth);
444     return Cost;
445   }
446 
447   /// Compute a bonus for replacing argument \p A with constant \p C.
448   InstructionCost getSpecializationBonus(Argument *A, Constant *C) {
449     Function *F = A->getParent();
450     DominatorTree DT(*F);
451     LoopInfo LI(DT);
452     auto &TTI = (GetTTI)(*F);
453     LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for: " << *A
454                       << "\n");
455 
456     InstructionCost TotalCost = 0;
457     for (auto *U : A->users()) {
458       TotalCost += getUserBonus(U, TTI, LI);
459       LLVM_DEBUG(dbgs() << "FnSpecialization: User cost ";
460                  TotalCost.print(dbgs()); dbgs() << " for: " << *U << "\n");
461     }
462 
463     // The below heuristic is only concerned with exposing inlining
464     // opportunities via indirect call promotion. If the argument is not a
465     // function pointer, give up.
466     if (!isa<PointerType>(A->getType()) ||
467         !isa<FunctionType>(A->getType()->getPointerElementType()))
468       return TotalCost;
469 
470     // Since the argument is a function pointer, its incoming constant values
471     // should be functions or constant expressions. The code below attempts to
472     // look through cast expressions to find the function that will be called.
473     Value *CalledValue = C;
474     while (isa<ConstantExpr>(CalledValue) &&
475            cast<ConstantExpr>(CalledValue)->isCast())
476       CalledValue = cast<User>(CalledValue)->getOperand(0);
477     Function *CalledFunction = dyn_cast<Function>(CalledValue);
478     if (!CalledFunction)
479       return TotalCost;
480 
481     // Get TTI for the called function (used for the inline cost).
482     auto &CalleeTTI = (GetTTI)(*CalledFunction);
483 
484     // Look at all the call sites whose called value is the argument.
485     // Specializing the function on the argument would allow these indirect
486     // calls to be promoted to direct calls. If the indirect call promotion
487     // would likely enable the called function to be inlined, specializing is a
488     // good idea.
489     int Bonus = 0;
490     for (User *U : A->users()) {
491       if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
492         continue;
493       auto *CS = cast<CallBase>(U);
494       if (CS->getCalledOperand() != A)
495         continue;
496 
497       // Get the cost of inlining the called function at this call site. Note
498       // that this is only an estimate. The called function may eventually
499       // change in a way that leads to it not being inlined here, even though
500       // inlining looks profitable now. For example, one of its called
501       // functions may be inlined into it, making the called function too large
502       // to be inlined into this call site.
503       //
504       // We apply a boost for performing indirect call promotion by increasing
505       // the default threshold by the threshold for indirect calls.
506       auto Params = getInlineParams();
507       Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
508       InlineCost IC =
509           getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
510 
511       // We clamp the bonus for this call to be between zero and the default
512       // threshold.
513       if (IC.isAlways())
514         Bonus += Params.DefaultThreshold;
515       else if (IC.isVariable() && IC.getCostDelta() > 0)
516         Bonus += IC.getCostDelta();
517     }
518 
519     return TotalCost + Bonus;
520   }
521 
522   /// Determine if we should specialize a function based on the incoming values
523   /// of the given argument.
524   ///
525   /// This function implements the goal-directed heuristic. It determines if
526   /// specializing the function based on the incoming values of argument \p A
527   /// would result in any significant optimization opportunities. If
528   /// optimization opportunities exist, the constant values of \p A on which to
529   /// specialize the function are collected in \p Constants. If the values in
530   /// \p Constants represent the complete set of values that \p A can take on,
531   /// the function will be completely specialized, and the \p IsPartial flag is
532   /// set to false.
533   ///
534   /// \returns true if the function should be specialized on the given
535   /// argument.
536   bool isArgumentInteresting(Argument *A,
537                              SmallVectorImpl<Constant *> &Constants,
538                              bool &IsPartial) {
539     Function *F = A->getParent();
540 
541     // For now, don't attempt to specialize functions based on the values of
542     // composite types.
543     if (!A->getType()->isSingleValueType() || A->user_empty())
544       return false;
545 
546     // If the argument isn't overdefined, there's nothing to do. It should
547     // already be constant.
548     if (!Solver.getLatticeValueFor(A).isOverdefined()) {
549       LLVM_DEBUG(dbgs() << "FnSpecialization: nothing to do, arg is already "
550                         << "constant?\n");
551       return false;
552     }
553 
554     // Collect the constant values that the argument can take on. If the
555     // argument can't take on any constant values, we aren't going to
556     // specialize the function. While it's possible to specialize the function
557     // based on non-constant arguments, there's likely not much benefit to
558     // constant propagation in doing so.
559     //
560     // TODO 1: currently it won't specialize if there are over the threshold of
561     // calls using the same argument, e.g foo(a) x 4 and foo(b) x 1, but it
562     // might be beneficial to take the occurrences into account in the cost
563     // model, so we would need to find the unique constants.
564     //
565     // TODO 2: this currently does not support constants, i.e. integer ranges.
566     //
567     SmallVector<Constant *, 4> PossibleConstants;
568     bool AllConstant = getPossibleConstants(A, PossibleConstants);
569     if (PossibleConstants.empty()) {
570       LLVM_DEBUG(dbgs() << "FnSpecialization: no possible constants found\n");
571       return false;
572     }
573     if (PossibleConstants.size() > MaxConstantsThreshold) {
574       LLVM_DEBUG(dbgs() << "FnSpecialization: number of constants found exceed "
575                         << "the maximum number of constants threshold.\n");
576       return false;
577     }
578 
579     // Determine if it would be profitable to create a specialization of the
580     // function where the argument takes on the given constant value. If so,
581     // add the constant to Constants.
582     auto FnSpecCost = getSpecializationCost(F);
583     if (!FnSpecCost.isValid()) {
584       LLVM_DEBUG(dbgs() << "FnSpecialization: Invalid specialisation cost.\n");
585       return false;
586     }
587 
588     LLVM_DEBUG(dbgs() << "FnSpecialization: func specialisation cost: ";
589                FnSpecCost.print(dbgs()); dbgs() << "\n");
590 
591     for (auto *C : PossibleConstants) {
592       LLVM_DEBUG(dbgs() << "FnSpecialization: Constant: " << *C << "\n");
593       if (ForceFunctionSpecialization) {
594         LLVM_DEBUG(dbgs() << "FnSpecialization: Forced!\n");
595         Constants.push_back(C);
596         continue;
597       }
598       if (getSpecializationBonus(A, C) > FnSpecCost) {
599         LLVM_DEBUG(dbgs() << "FnSpecialization: profitable!\n");
600         Constants.push_back(C);
601       } else {
602         LLVM_DEBUG(dbgs() << "FnSpecialization: not profitable\n");
603       }
604     }
605 
606     // None of the constant values the argument can take on were deemed good
607     // candidates on which to specialize the function.
608     if (Constants.empty())
609       return false;
610 
611     // This will be a partial specialization if some of the constants were
612     // rejected due to their profitability.
613     IsPartial = !AllConstant || PossibleConstants.size() != Constants.size();
614 
615     return true;
616   }
617 
618   /// Collect in \p Constants all the constant values that argument \p A can
619   /// take on.
620   ///
621   /// \returns true if all of the values the argument can take on are constant
622   /// (e.g., the argument's parent function cannot be called with an
623   /// overdefined value).
624   bool getPossibleConstants(Argument *A,
625                             SmallVectorImpl<Constant *> &Constants) {
626     Function *F = A->getParent();
627     bool AllConstant = true;
628 
629     // Iterate over all the call sites of the argument's parent function.
630     for (User *U : F->users()) {
631       if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
632         continue;
633       auto &CS = *cast<CallBase>(U);
634 
635       // If the parent of the call site will never be executed, we don't need
636       // to worry about the passed value.
637       if (!Solver.isBlockExecutable(CS.getParent()))
638         continue;
639 
640       auto *V = CS.getArgOperand(A->getArgNo());
641       // TrackValueOfGlobalVariable only tracks scalar global variables.
642       if (auto *GV = dyn_cast<GlobalVariable>(V)) {
643         if (!GV->getValueType()->isSingleValueType()) {
644           return false;
645         }
646       }
647 
648       if (isa<Constant>(V) && (Solver.getLatticeValueFor(V).isConstant() ||
649                                EnableSpecializationForLiteralConstant))
650         Constants.push_back(cast<Constant>(V));
651       else
652         AllConstant = false;
653     }
654 
655     // If the argument can only take on constant values, AllConstant will be
656     // true.
657     return AllConstant;
658   }
659 
660   /// Rewrite calls to function \p F to call function \p Clone instead.
661   ///
662   /// This function modifies calls to function \p F whose argument at index \p
663   /// ArgNo is equal to constant \p C. The calls are rewritten to call function
664   /// \p Clone instead.
665   void rewriteCallSites(Function *F, Function *Clone, Argument &Arg,
666                         Constant *C) {
667     unsigned ArgNo = Arg.getArgNo();
668     SmallVector<CallBase *, 4> CallSitesToRewrite;
669     for (auto *U : F->users()) {
670       if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
671         continue;
672       auto &CS = *cast<CallBase>(U);
673       if (!CS.getCalledFunction() || CS.getCalledFunction() != F)
674         continue;
675       CallSitesToRewrite.push_back(&CS);
676     }
677     for (auto *CS : CallSitesToRewrite) {
678       if ((CS->getFunction() == Clone && CS->getArgOperand(ArgNo) == &Arg) ||
679           CS->getArgOperand(ArgNo) == C) {
680         CS->setCalledFunction(Clone);
681         Solver.markOverdefined(CS);
682       }
683     }
684   }
685 };
686 
687 bool llvm::runFunctionSpecialization(
688     Module &M, const DataLayout &DL,
689     std::function<TargetLibraryInfo &(Function &)> GetTLI,
690     std::function<TargetTransformInfo &(Function &)> GetTTI,
691     std::function<AssumptionCache &(Function &)> GetAC,
692     function_ref<AnalysisResultsForFn(Function &)> GetAnalysis) {
693   SCCPSolver Solver(DL, GetTLI, M.getContext());
694   FunctionSpecializer FS(Solver, GetAC, GetTTI, GetTLI);
695   bool Changed = false;
696 
697   // Loop over all functions, marking arguments to those with their addresses
698   // taken or that are external as overdefined.
699   for (Function &F : M) {
700     if (F.isDeclaration())
701       continue;
702     if (F.hasFnAttribute(Attribute::NoDuplicate))
703       continue;
704 
705     LLVM_DEBUG(dbgs() << "\nFnSpecialization: Analysing decl: " << F.getName()
706                       << "\n");
707     Solver.addAnalysis(F, GetAnalysis(F));
708 
709     // Determine if we can track the function's arguments. If so, add the
710     // function to the solver's set of argument-tracked functions.
711     if (canTrackArgumentsInterprocedurally(&F)) {
712       LLVM_DEBUG(dbgs() << "FnSpecialization: Can track arguments\n");
713       Solver.addArgumentTrackedFunction(&F);
714       continue;
715     } else {
716       LLVM_DEBUG(dbgs() << "FnSpecialization: Can't track arguments!\n"
717                         << "FnSpecialization: Doesn't have local linkage, or "
718                         << "has its address taken\n");
719     }
720 
721     // Assume the function is called.
722     Solver.markBlockExecutable(&F.front());
723 
724     // Assume nothing about the incoming arguments.
725     for (Argument &AI : F.args())
726       Solver.markOverdefined(&AI);
727   }
728 
729   // Determine if we can track any of the module's global variables. If so, add
730   // the global variables we can track to the solver's set of tracked global
731   // variables.
732   for (GlobalVariable &G : M.globals()) {
733     G.removeDeadConstantUsers();
734     if (canTrackGlobalVariableInterprocedurally(&G))
735       Solver.trackValueOfGlobalVariable(&G);
736   }
737 
738   // Solve for constants.
739   auto RunSCCPSolver = [&](auto &WorkList) {
740     bool ResolvedUndefs = true;
741 
742     while (ResolvedUndefs) {
743       LLVM_DEBUG(dbgs() << "FnSpecialization: Running solver\n");
744       Solver.solve();
745       LLVM_DEBUG(dbgs() << "FnSpecialization: Resolving undefs\n");
746       ResolvedUndefs = false;
747       for (Function *F : WorkList)
748         if (Solver.resolvedUndefsIn(*F))
749           ResolvedUndefs = true;
750     }
751 
752     for (auto *F : WorkList) {
753       for (BasicBlock &BB : *F) {
754         if (!Solver.isBlockExecutable(&BB))
755           continue;
756         for (auto &I : make_early_inc_range(BB))
757           FS.tryToReplaceWithConstant(&I);
758       }
759     }
760   };
761 
762   auto &TrackedFuncs = Solver.getArgumentTrackedFunctions();
763   SmallVector<Function *, 16> FuncDecls(TrackedFuncs.begin(),
764                                         TrackedFuncs.end());
765 #ifndef NDEBUG
766   LLVM_DEBUG(dbgs() << "FnSpecialization: Worklist fn decls:\n");
767   for (auto *F : FuncDecls)
768     LLVM_DEBUG(dbgs() << "FnSpecialization: *) " << F->getName() << "\n");
769 #endif
770 
771   // Initially resolve the constants in all the argument tracked functions.
772   RunSCCPSolver(FuncDecls);
773 
774   SmallVector<Function *, 2> CurrentSpecializations;
775   unsigned I = 0;
776   while (FuncSpecializationMaxIters != I++ &&
777          FS.specializeFunctions(FuncDecls, CurrentSpecializations)) {
778 
779     // Run the solver for the specialized functions.
780     RunSCCPSolver(CurrentSpecializations);
781 
782     // Replace some unresolved constant arguments
783     constantArgPropagation(FuncDecls, M, Solver);
784 
785     CurrentSpecializations.clear();
786     Changed = true;
787   }
788 
789   // Clean up the IR by removing ssa_copy intrinsics.
790   removeSSACopy(M);
791   return Changed;
792 }
793