LLVM 24.0.0git
FunctionSpecialization.cpp
Go to the documentation of this file.
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
10#include "llvm/ADT/Statistic.h"
23
24using namespace llvm;
25
26#define DEBUG_TYPE "function-specialization"
27
28STATISTIC(NumSpecsCreated, "Number of specializations created");
29
30namespace llvm {
31
33 "force-specialization", cl::init(false), cl::Hidden,
35 "Force function specialization for every call site with a constant "
36 "argument"));
37
39 "funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc(
40 "The maximum number of clones allowed for a single function "
41 "specialization"));
42
44 MaxDiscoveryIterations("funcspec-max-discovery-iterations", cl::init(100),
46 cl::desc("The maximum number of iterations allowed "
47 "when searching for transitive "
48 "phis"));
49
51 "funcspec-max-incoming-phi-values", cl::init(8), cl::Hidden,
52 cl::desc("The maximum number of incoming values a PHI node can have to be "
53 "considered during the specialization bonus estimation"));
54
56 "funcspec-max-block-predecessors", cl::init(2), cl::Hidden, cl::desc(
57 "The maximum number of predecessors a basic block can have to be "
58 "considered during the estimation of dead code"));
59
61 "funcspec-min-function-size", cl::init(500), cl::Hidden,
62 cl::desc("Don't specialize functions that have less than this number of "
63 "instructions"));
64
66 "funcspec-max-codesize-growth", cl::init(3), cl::Hidden, cl::desc(
67 "Maximum codesize growth allowed per function"));
68
70 "funcspec-min-codesize-savings", cl::init(20), cl::Hidden,
71 cl::desc("Reject specializations whose codesize savings are less than this "
72 "much percent of the original function size"));
73
75 "funcspec-min-latency-savings", cl::init(20), cl::Hidden,
76 cl::desc("Reject specializations whose latency savings are less than this "
77 "much percent of the original function size"));
78
80 "funcspec-min-inlining-bonus", cl::init(300), cl::Hidden,
81 cl::desc("Reject specializations whose inlining bonus is less than this "
82 "much percent of the original function size"));
83
85 "funcspec-on-address", cl::init(false), cl::Hidden, cl::desc(
86 "Enable function specialization on the address of global values"));
87
89 "funcspec-for-literal-constant", cl::init(true), cl::Hidden,
91 "Enable specialization of functions that take a literal constant as an "
92 "argument"));
93
94} // end namespace llvm
95
96bool InstCostVisitor::canEliminateSuccessor(BasicBlock *BB,
97 BasicBlock *Succ) const {
98 unsigned I = 0;
99 return all_of(predecessors(Succ), [&I, BB, Succ, this](BasicBlock *Pred) {
100 return I++ < MaxBlockPredecessors &&
101 (Pred == BB || Pred == Succ || !isBlockExecutable(Pred));
102 });
103}
104
105// Estimates the codesize savings due to dead code after constant propagation.
106// \p WorkList represents the basic blocks of a specialization which will
107// eventually become dead once we replace instructions that are known to be
108// constants. The successors of such blocks are added to the list as long as
109// the \p Solver found they were executable prior to specialization, and only
110// if all their predecessors are dead.
111Cost InstCostVisitor::estimateBasicBlocks(
113 Cost CodeSize = 0;
114 // Accumulate the codesize savings of each basic block.
115 while (!WorkList.empty()) {
116 BasicBlock *BB = WorkList.pop_back_val();
117
118 // These blocks are considered dead as far as the InstCostVisitor
119 // is concerned. They haven't been proven dead yet by the Solver,
120 // but may become if we propagate the specialization arguments.
121 assert(Solver.isBlockExecutable(BB) && "BB already found dead by IPSCCP!");
122 if (!DeadBlocks.insert(BB).second)
123 continue;
124
125 for (Instruction &I : *BB) {
126 // If it's a known constant we have already accounted for it.
127 if (KnownConstants.contains(&I))
128 continue;
129
130 Cost C = TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
131
132 LLVM_DEBUG(dbgs() << "FnSpecialization: CodeSize " << C
133 << " for user " << I << "\n");
134 CodeSize += C;
135 }
136
137 // Keep adding dead successors to the list as long as they are
138 // executable and only reachable from dead blocks.
139 for (BasicBlock *SuccBB : successors(BB))
140 if (isBlockExecutable(SuccBB) && canEliminateSuccessor(BB, SuccBB))
141 WorkList.push_back(SuccBB);
142 }
143 return CodeSize;
144}
145
146Constant *InstCostVisitor::findConstantFor(Value *V) const {
147 if (auto *C = dyn_cast<Constant>(V))
148 return C;
149 if (auto *C = Solver.getConstantOrNull(V))
150 return C;
151 return KnownConstants.lookup(V);
152}
153
156 while (!PendingPHIs.empty()) {
157 Instruction *Phi = PendingPHIs.pop_back_val();
158 // The pending PHIs could have been proven dead by now.
159 if (isBlockExecutable(Phi->getParent()))
160 CodeSize += getCodeSizeSavingsForUser(Phi);
161 }
162 return CodeSize;
163}
164
165/// Compute the codesize savings for replacing argument \p A with constant \p C.
167 LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: "
168 << C->getNameOrAsOperand() << "\n");
170 for (auto *U : A->users())
171 if (auto *UI = dyn_cast<Instruction>(U))
172 if (isBlockExecutable(UI->getParent()))
173 CodeSize += getCodeSizeSavingsForUser(UI, A, C);
174
175 LLVM_DEBUG(dbgs() << "FnSpecialization: Accumulated bonus {CodeSize = "
176 << CodeSize << "} for argument " << *A << "\n");
177 return CodeSize;
178}
179
180/// Compute the latency savings from replacing all arguments with constants for
181/// a specialization candidate. As this function computes the latency savings
182/// for all Instructions in KnownConstants at once, it should be called only
183/// after every instruction has been visited, i.e. after:
184///
185/// * getCodeSizeSavingsForArg has been run for every constant argument of a
186/// specialization candidate
187///
188/// * getCodeSizeSavingsFromPendingPHIs has been run
189///
190/// to ensure that the latency savings are calculated for all Instructions we
191/// have visited and found to be constant.
193 auto &BFI = GetBFI(*F);
194 Cost TotalLatency = 0;
195
196 for (auto Pair : KnownConstants) {
197 Instruction *I = dyn_cast<Instruction>(Pair.first);
198 if (!I)
199 continue;
200
201 uint64_t Weight = BFI.getBlockFreq(I->getParent()).getFrequency() /
202 BFI.getEntryFreq().getFrequency();
203
204 Cost Latency =
205 Weight * TTI.getInstructionCost(I, TargetTransformInfo::TCK_Latency);
206
207 LLVM_DEBUG(dbgs() << "FnSpecialization: {Latency = " << Latency
208 << "} for instruction " << *I << "\n");
209
210 TotalLatency += Latency;
211 }
212
213 return TotalLatency;
214}
215
216Cost InstCostVisitor::getCodeSizeSavingsForUser(Instruction *User, Value *Use,
217 Constant *C) {
218 // We have already propagated a constant for this user.
219 if (KnownConstants.contains(User))
220 return 0;
221
222 // Cache the iterator before visiting.
223 LastVisited = Use ? KnownConstants.insert({Use, C}).first
224 : KnownConstants.end();
225
226 Cost CodeSize = 0;
227 if (auto *I = dyn_cast<SwitchInst>(User)) {
228 CodeSize = estimateSwitchInst(*I);
229 } else if (auto *I = dyn_cast<CondBrInst>(User)) {
230 CodeSize = estimateCondBrInst(*I);
231 } else {
232 C = visit(*User);
233 if (!C)
234 return 0;
235 }
236
237 // Even though it doesn't make sense to bind switch and branch instructions
238 // with a constant, unlike any other instruction type, it prevents estimating
239 // their bonus multiple times.
240 KnownConstants.insert({User, C});
241
242 CodeSize += TTI.getInstructionCost(User, TargetTransformInfo::TCK_CodeSize);
243
244 LLVM_DEBUG(dbgs() << "FnSpecialization: {CodeSize = " << CodeSize
245 << "} for user " << *User << "\n");
246
247 for (auto *U : User->users())
248 if (auto *UI = dyn_cast<Instruction>(U))
249 if (UI != User && isBlockExecutable(UI->getParent()))
250 CodeSize += getCodeSizeSavingsForUser(UI, User, C);
251
252 return CodeSize;
253}
254
255Cost InstCostVisitor::estimateSwitchInst(SwitchInst &I) {
256 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
257
258 if (I.getCondition() != LastVisited->first)
259 return 0;
260
261 auto *C = dyn_cast<ConstantInt>(LastVisited->second);
262 if (!C)
263 return 0;
264
265 BasicBlock *Succ = I.findCaseValue(C)->getCaseSuccessor();
266 // Initialize the worklist with the dead basic blocks. These are the
267 // destination labels which are different from the one corresponding
268 // to \p C. They should be executable and have a unique predecessor.
270 for (const auto &Case : I.cases()) {
271 BasicBlock *BB = Case.getCaseSuccessor();
272 if (BB != Succ && isBlockExecutable(BB) &&
273 canEliminateSuccessor(I.getParent(), BB))
274 WorkList.push_back(BB);
275 }
276
277 return estimateBasicBlocks(WorkList);
278}
279
280Cost InstCostVisitor::estimateCondBrInst(CondBrInst &I) {
281 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
282
283 if (I.getCondition() != LastVisited->first)
284 return 0;
285
286 BasicBlock *Succ = I.getSuccessor(LastVisited->second->isOneValue());
287 // Initialize the worklist with the dead successor as long as
288 // it is executable and has a unique predecessor.
290 if (isBlockExecutable(Succ) && canEliminateSuccessor(I.getParent(), Succ))
291 WorkList.push_back(Succ);
292
293 return estimateBasicBlocks(WorkList);
294}
295
296bool InstCostVisitor::discoverTransitivelyIncomingValues(
297 Constant *Const, PHINode *Root, DenseSet<PHINode *> &TransitivePHIs) {
298
300 WorkList.push_back(Root);
301 unsigned Iter = 0;
302
303 while (!WorkList.empty()) {
304 PHINode *PN = WorkList.pop_back_val();
305
306 if (++Iter > MaxDiscoveryIterations ||
308 return false;
309
310 if (!TransitivePHIs.insert(PN).second)
311 continue;
312
313 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
314 Value *V = PN->getIncomingValue(I);
315
316 // Disregard self-references and dead incoming values.
317 if (auto *Inst = dyn_cast<Instruction>(V))
318 if (Inst == PN || !isBlockExecutable(PN->getIncomingBlock(I)))
319 continue;
320
321 if (Constant *C = findConstantFor(V)) {
322 // Not all incoming values are the same constant. Bail immediately.
323 if (C != Const)
324 return false;
325 continue;
326 }
327
328 if (auto *Phi = dyn_cast<PHINode>(V)) {
329 WorkList.push_back(Phi);
330 continue;
331 }
332
333 // We can't reason about anything else.
334 return false;
335 }
336 }
337 return true;
338}
339
340Constant *InstCostVisitor::visitPHINode(PHINode &I) {
341 if (I.getNumIncomingValues() > MaxIncomingPhiValues)
342 return nullptr;
343
344 bool Inserted = VisitedPHIs.insert(&I).second;
345 Constant *Const = nullptr;
346 bool HaveSeenIncomingPHI = false;
347
348 for (unsigned Idx = 0, E = I.getNumIncomingValues(); Idx != E; ++Idx) {
349 Value *V = I.getIncomingValue(Idx);
350
351 // Disregard self-references and dead incoming values.
352 if (auto *Inst = dyn_cast<Instruction>(V))
353 if (Inst == &I || !isBlockExecutable(I.getIncomingBlock(Idx)))
354 continue;
355
356 if (Constant *C = findConstantFor(V)) {
357 if (!Const)
358 Const = C;
359 // Not all incoming values are the same constant. Bail immediately.
360 if (C != Const)
361 return nullptr;
362 continue;
363 }
364
365 if (Inserted) {
366 // First time we are seeing this phi. We will retry later, after
367 // all the constant arguments have been propagated. Bail for now.
368 PendingPHIs.push_back(&I);
369 return nullptr;
370 }
371
372 if (isa<PHINode>(V)) {
373 // Perhaps it is a Transitive Phi. We will confirm later.
374 HaveSeenIncomingPHI = true;
375 continue;
376 }
377
378 // We can't reason about anything else.
379 return nullptr;
380 }
381
382 if (!Const)
383 return nullptr;
384
385 if (!HaveSeenIncomingPHI)
386 return Const;
387
388 DenseSet<PHINode *> TransitivePHIs;
389 if (!discoverTransitivelyIncomingValues(Const, &I, TransitivePHIs))
390 return nullptr;
391
392 return Const;
393}
394
395Constant *InstCostVisitor::visitFreezeInst(FreezeInst &I) {
396 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
397
398 if (isGuaranteedNotToBeUndefOrPoison(LastVisited->second))
399 return LastVisited->second;
400 return nullptr;
401}
402
403Constant *InstCostVisitor::visitCallBase(CallBase &I) {
404 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
405
406 Function *F = I.getCalledFunction();
407 if (!F || !canConstantFoldCallTo(&I, F))
408 return nullptr;
409
411 Operands.reserve(I.getNumOperands());
412
413 for (unsigned Idx = 0, E = I.getNumOperands() - 1; Idx != E; ++Idx) {
414 Value *V = I.getOperand(Idx);
416 return nullptr;
417 Constant *C = findConstantFor(V);
418 if (!C)
419 return nullptr;
420 Operands.push_back(C);
421 }
422
423 auto Ops = ArrayRef(Operands.begin(), Operands.end());
424 return ConstantFoldCall(&I, F, Ops);
425}
426
427Constant *InstCostVisitor::visitLoadInst(LoadInst &I) {
428 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
429
430 if (isa<ConstantPointerNull>(LastVisited->second))
431 return nullptr;
432 return ConstantFoldLoadFromConstPtr(LastVisited->second, I.getType(), DL);
433}
434
435Constant *InstCostVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
437 Operands.reserve(I.getNumOperands());
438
439 for (unsigned Idx = 0, E = I.getNumOperands(); Idx != E; ++Idx) {
440 Value *V = I.getOperand(Idx);
441 Constant *C = findConstantFor(V);
442 if (!C)
443 return nullptr;
444 Operands.push_back(C);
445 }
446
447 auto Ops = ArrayRef(Operands.begin(), Operands.end());
448 return ConstantFoldInstOperands(&I, Ops, DL);
449}
450
451Constant *InstCostVisitor::visitSelectInst(SelectInst &I) {
452 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
453
454 if (I.getCondition() == LastVisited->first) {
455 Value *V = LastVisited->second->isNullValue() ? I.getFalseValue()
456 : I.getTrueValue();
457 return findConstantFor(V);
458 }
459 if (Constant *Condition = findConstantFor(I.getCondition()))
460 if ((I.getTrueValue() == LastVisited->first && Condition->isOneValue()) ||
461 (I.getFalseValue() == LastVisited->first && Condition->isNullValue()))
462 return LastVisited->second;
463 return nullptr;
464}
465
466Constant *InstCostVisitor::visitCastInst(CastInst &I) {
467 return ConstantFoldCastOperand(I.getOpcode(), LastVisited->second,
468 I.getType(), DL);
469}
470
471Constant *InstCostVisitor::visitCmpInst(CmpInst &I) {
472 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
473
474 Constant *Const = LastVisited->second;
475 bool ConstOnRHS = I.getOperand(1) == LastVisited->first;
476 Value *V = ConstOnRHS ? I.getOperand(0) : I.getOperand(1);
477 Constant *Other = findConstantFor(V);
478
479 if (Other) {
480 if (ConstOnRHS)
481 std::swap(Const, Other);
482 return ConstantFoldCompareInstOperands(I.getPredicate(), Const, Other, DL);
483 }
484
485 // If we haven't found Other to be a specific constant value, we may still be
486 // able to constant fold using information from the lattice value.
487 const ValueLatticeElement &ConstLV = ValueLatticeElement::get(Const);
488 const ValueLatticeElement &OtherLV = Solver.getLatticeValueFor(V);
489 auto &V1State = ConstOnRHS ? OtherLV : ConstLV;
490 auto &V2State = ConstOnRHS ? ConstLV : OtherLV;
491 return V1State.getCompare(I.getPredicate(), I.getType(), V2State, DL);
492}
493
494Constant *InstCostVisitor::visitUnaryOperator(UnaryOperator &I) {
495 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
496
497 return ConstantFoldUnaryOpOperand(I.getOpcode(), LastVisited->second, DL);
498}
499
500Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) {
501 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
502
503 bool ConstOnRHS = I.getOperand(1) == LastVisited->first;
504 Value *V = ConstOnRHS ? I.getOperand(0) : I.getOperand(1);
505 Constant *Other = findConstantFor(V);
506 Value *OtherVal = Other ? Other : V;
507 Value *ConstVal = LastVisited->second;
508
509 if (ConstOnRHS)
510 std::swap(ConstVal, OtherVal);
511
513 simplifyBinOp(I.getOpcode(), ConstVal, OtherVal, SimplifyQuery(DL)));
514}
515
516Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca,
517 CallInst *Call) {
518 Value *StoreValue = nullptr;
519 for (auto *User : Alloca->users()) {
520 // We can't use llvm::isAllocaPromotable() as that would fail because of
521 // the usage in the CallInst, which is what we check here.
522 if (User == Call)
523 continue;
524
525 if (auto *Store = dyn_cast<StoreInst>(User)) {
526 // This is a duplicate store, bail out.
527 if (StoreValue || Store->isVolatile())
528 return nullptr;
529 StoreValue = Store->getValueOperand();
530 continue;
531 }
532 // Bail if there is any other unknown usage.
533 return nullptr;
534 }
535
536 if (!StoreValue)
537 return nullptr;
538
539 return getCandidateConstant(StoreValue);
540}
541
542// A constant stack value is an AllocaInst that has a single constant
543// value stored to it. Return this constant if such an alloca stack value
544// is a function argument and the value is an integer.
545Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call,
546 Value *Val) {
547 if (!Val)
548 return nullptr;
549 Val = Val->stripPointerCasts();
550 auto *Alloca = dyn_cast<AllocaInst>(Val);
551 if (!Alloca)
552 return nullptr;
553 Constant *C = getPromotableAlloca(Alloca, Call);
554 if (!C || !C->getType()->isIntegerTy())
555 return nullptr;
556 return C;
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.
582void 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,
606 "specialized.arg." + Twine(++NGlobals));
607 Call->setArgOperand(Idx, GV);
608 }
609 }
610}
611
612// The SCCP solver inserts bitcasts for PredicateInfo. These interfere with the
613// promoteConstantStackValues() optimization.
614static void removeSSACopy(Function &F) {
615 for (BasicBlock &BB : F) {
616 for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
617 auto *BC = dyn_cast<BitCastInst>(&Inst);
618 if (!BC || BC->getType() != BC->getOperand(0)->getType())
619 continue;
620 Inst.replaceAllUsesWith(BC->getOperand(0));
621 Inst.eraseFromParent();
622 }
623 }
624}
625
626/// Remove any ssa_copy intrinsics that may have been introduced.
627void FunctionSpecializer::cleanUpSSA() {
628 for (Function *F : Specializations)
630}
631
632template <> struct llvm::DenseMapInfo<SpecSig> {
633 static unsigned getHashValue(const SpecSig &S) {
634 return static_cast<unsigned>(hash_value(S));
635 }
636
637 static bool isEqual(const SpecSig &LHS, const SpecSig &RHS) {
638 return LHS == RHS;
639 }
640};
641
644 if (NumSpecsCreated > 0)
645 dbgs() << "FnSpecialization: Created " << NumSpecsCreated
646 << " specializations in module " << M.getName() << "\n");
647 // Eliminate dead code.
648 removeDeadFunctions();
649 cleanUpSSA();
650}
651
652/// Get the unsigned Value of given Cost object. Assumes the Cost is always
653/// non-negative, which is true for both TCK_CodeSize and TCK_Latency, and
654/// always Valid.
655static unsigned getCostValue(const Cost &C) {
656 int64_t Value = C.getValue();
657
658 assert(Value >= 0 && "CodeSize and Latency cannot be negative");
659 // It is safe to down cast since we know the arguments cannot be negative and
660 // Cost is of type int64_t.
661 return static_cast<unsigned>(Value);
662}
663
664/// Attempt to specialize functions in the module to enable constant
665/// propagation across function boundaries.
666///
667/// \returns true if at least one function is specialized.
669 // Find possible specializations for each function.
670 SpecMap SM;
671 SmallVector<Spec, 32> AllSpecs;
672 unsigned NumCandidates = 0;
673 for (Function &F : M) {
674 if (!isCandidateFunction(&F))
675 continue;
676
677 auto [It, Inserted] = FunctionMetrics.try_emplace(&F);
678 CodeMetrics &Metrics = It->second;
679 //Analyze the function.
680 if (Inserted) {
682 CodeMetrics::collectEphemeralValues(&F, &GetAC(F), EphValues);
683 for (BasicBlock &BB : F)
684 Metrics.analyzeBasicBlock(&BB, GetTTI(F), EphValues);
685 }
686
687 // When specializing literal constants is enabled, always require functions
688 // to be larger than MinFunctionSize, to prevent excessive specialization.
689 const bool RequireMinSize =
691 (SpecializeLiteralConstant || !F.hasFnAttribute(Attribute::NoInline));
692
693 // If the code metrics reveal that we shouldn't duplicate the function,
694 // or if the code size implies that this function is easy to get inlined,
695 // then we shouldn't specialize it.
696 if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() ||
697 (RequireMinSize && Metrics.NumInsts < MinFunctionSize))
698 continue;
699
700 // When specialization on literal constants is disabled, only consider
701 // recursive functions when running multiple times to save wasted analysis,
702 // as we will not be able to specialize on any newly found literal constant
703 // return values.
704 if (!SpecializeLiteralConstant && !Inserted && !Metrics.isRecursive)
705 continue;
706
707 int64_t Sz = Metrics.NumInsts.getValue();
708 assert(Sz > 0 && "CodeSize should be positive");
709 // It is safe to down cast from int64_t, NumInsts is always positive.
710 unsigned FuncSize = static_cast<unsigned>(Sz);
711
712 LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for "
713 << F.getName() << " is " << FuncSize << "\n");
714
715 if (Inserted && Metrics.isRecursive)
716 promoteConstantStackValues(&F);
717
718 if (!findSpecializations(&F, FuncSize, AllSpecs, SM)) {
720 dbgs() << "FnSpecialization: No possible specializations found for "
721 << F.getName() << "\n");
722 continue;
723 }
724
725 ++NumCandidates;
726 }
727
728 if (!NumCandidates) {
730 dbgs()
731 << "FnSpecialization: No possible specializations found in module\n");
732 return false;
733 }
734
735 // Choose the most profitable specialisations, which fit in the module
736 // specialization budget, which is derived from maximum number of
737 // specializations per specialization candidate function.
738 auto CompareScore = [&AllSpecs](unsigned I, unsigned J) {
739 if (AllSpecs[I].Score != AllSpecs[J].Score)
740 return AllSpecs[I].Score > AllSpecs[J].Score;
741 return I > J;
742 };
743 const unsigned NSpecs =
744 std::min(NumCandidates * MaxClones, unsigned(AllSpecs.size()));
745 SmallVector<unsigned> BestSpecs(NSpecs + 1);
746 std::iota(BestSpecs.begin(), BestSpecs.begin() + NSpecs, 0);
747 if (AllSpecs.size() > NSpecs) {
748 LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed "
749 << "the maximum number of clones threshold.\n"
750 << "FnSpecialization: Specializing the "
751 << NSpecs
752 << " most profitable candidates.\n");
753 std::make_heap(BestSpecs.begin(), BestSpecs.begin() + NSpecs, CompareScore);
754 for (unsigned I = NSpecs, N = AllSpecs.size(); I < N; ++I) {
755 BestSpecs[NSpecs] = I;
756 std::push_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
757 std::pop_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
758 }
759 }
760
761 LLVM_DEBUG(dbgs() << "FnSpecialization: List of specializations \n";
762 for (unsigned I = 0; I < NSpecs; ++I) {
763 const Spec &S = AllSpecs[BestSpecs[I]];
764 dbgs() << "FnSpecialization: Function " << S.F->getName()
765 << " , score " << S.Score << "\n";
766 for (const ArgInfo &Arg : S.Sig.Args)
767 dbgs() << "FnSpecialization: FormalArg = "
768 << Arg.Formal->getNameOrAsOperand()
769 << ", ActualArg = " << Arg.Actual->getNameOrAsOperand()
770 << "\n";
771 });
772
773 // Create the chosen specializations.
774 SmallPtrSet<Function *, 8> OriginalFuncs;
776 for (unsigned I = 0; I < NSpecs; ++I) {
777 Spec &S = AllSpecs[BestSpecs[I]];
778
779 // Accumulate the codesize growth for the function, now we are creating the
780 // specialization.
781 FunctionGrowth[S.F] += S.CodeSize;
782
783 S.Clone = createSpecialization(S.F, S.Sig);
784
785 // Update the known call sites to call the clone.
786 for (CallBase *Call : S.CallSites) {
787 Function *Clone = S.Clone;
788 LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call
789 << " to call " << Clone->getName() << "\n");
790 Call->setCalledFunction(S.Clone);
791 auto &BFI = GetBFI(*Call->getFunction());
792 std::optional<uint64_t> Count =
793 BFI.getBlockProfileCount(Call->getParent());
794 if (Count) {
795 std::optional<uint64_t> MaybeCloneCount = Clone->getEntryCount();
796 if (MaybeCloneCount) {
797 uint64_t CallCount = *Count + *MaybeCloneCount;
798 Clone->setEntryCount(CallCount);
799 if (std::optional<uint64_t> MaybeOriginalCount =
800 S.F->getEntryCount()) {
801 uint64_t OriginalCount = *MaybeOriginalCount;
802 if (OriginalCount >= *Count) {
803 S.F->setEntryCount(OriginalCount - *Count);
804 } else {
805 // This should generally not happen as that would mean there are
806 // more computed calls to the function than what was recorded.
808 }
809 }
810 }
811 }
812 }
813
814 Clones.push_back(S.Clone);
815 OriginalFuncs.insert(S.F);
816 }
817
818 Solver.solveWhileResolvedUndefsIn(Clones);
819
820 // Update the rest of the call sites - these are the recursive calls, calls
821 // to discarded specialisations and calls that may match a specialisation
822 // after the solver runs.
823 for (Function *F : OriginalFuncs) {
824 auto [Begin, End] = SM[F];
825 updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End);
826 }
827
828 for (Function *F : Clones) {
829 if (F->getReturnType()->isVoidTy())
830 continue;
831 if (F->getReturnType()->isStructTy()) {
832 auto *STy = cast<StructType>(F->getReturnType());
833 if (!Solver.isStructLatticeConstant(F, STy))
834 continue;
835 } else {
836 auto It = Solver.getTrackedRetVals().find(F);
837 assert(It != Solver.getTrackedRetVals().end() &&
838 "Return value ought to be tracked");
839 if (SCCPSolver::isOverdefined(It->second))
840 continue;
841 }
842 for (User *U : F->users()) {
843 if (auto *CS = dyn_cast<CallBase>(U)) {
844 //The user instruction does not call our function.
845 if (CS->getCalledFunction() != F)
846 continue;
847 Solver.resetLatticeValueFor(CS);
848 }
849 }
850 }
851
852 // Rerun the solver to notify the users of the modified callsites.
853 Solver.solveWhileResolvedUndefs();
854
855 for (Function *F : OriginalFuncs)
856 if (FunctionMetrics[F].isRecursive)
857 promoteConstantStackValues(F);
858
859 return true;
860}
861
862void FunctionSpecializer::removeDeadFunctions() {
863 for (Function *F : DeadFunctions) {
864 LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function "
865 << F->getName() << "\n");
866 if (FAM)
867 FAM->clear(*F, F->getName());
868
869 // Remove all the callsites that were proven unreachable once, and replace
870 // them with poison.
871 for (User *U : make_early_inc_range(F->users())) {
873 "User of dead function must be call or invoke");
876 CS->eraseFromParent();
877 }
878 F->eraseFromParent();
879 }
880 DeadFunctions.clear();
881}
882
883/// Clone the function \p F and remove the ssa_copy intrinsics added by
884/// the SCCPSolver in the cloned version.
885static Function *cloneCandidateFunction(Function *F, unsigned NSpecs) {
886 ValueToValueMapTy Mappings;
887 Function *Clone = CloneFunction(F, Mappings);
888 Clone->setName(F->getName() + ".specialized." + Twine(NSpecs));
889 removeSSACopy(*Clone);
890 return Clone;
891}
892
893bool FunctionSpecializer::findSpecializations(Function *F, unsigned FuncSize,
894 SmallVectorImpl<Spec> &AllSpecs,
895 SpecMap &SM) {
896 // A mapping from a specialisation signature to the index of the respective
897 // entry in the all specialisation array. Used to ensure uniqueness of
898 // specialisations.
899 DenseMap<SpecSig, unsigned> UniqueSpecs;
900
901 // Get a list of interesting arguments.
903 for (Argument &Arg : F->args())
904 if (isArgumentInteresting(&Arg))
905 Args.push_back(&Arg);
906
907 if (Args.empty())
908 return false;
909
910 for (User *U : F->users()) {
911 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
912 continue;
913 auto &CS = *cast<CallBase>(U);
914
915 // The user instruction does not call our function.
916 if (CS.getCalledFunction() != F)
917 continue;
918
919 // If the call site has attribute minsize set, that callsite won't be
920 // specialized.
921 if (CS.hasFnAttr(Attribute::MinSize))
922 continue;
923
924 // If the parent of the call site will never be executed, we don't need
925 // to worry about the passed value.
926 if (!Solver.isBlockExecutable(CS.getParent()))
927 continue;
928
929 // Examine arguments and create a specialisation candidate from the
930 // constant operands of this call site.
931 SpecSig S;
932 for (Argument *A : Args) {
933 Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo()));
934 if (!C)
935 continue;
936 LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument "
937 << A->getName() << " : " << C->getNameOrAsOperand()
938 << "\n");
939 S.Args.push_back({A, C});
940 }
941
942 if (S.Args.empty())
943 continue;
944
945 // Check if we have encountered the same specialisation already.
946 if (auto It = UniqueSpecs.find(S); It != UniqueSpecs.end()) {
947 // Existing specialisation. Add the call to the list to rewrite, unless
948 // it's a recursive call. A specialisation, generated because of a
949 // recursive call may end up as not the best specialisation for all
950 // the cloned instances of this call, which result from specialising
951 // functions. Hence we don't rewrite the call directly, but match it with
952 // the best specialisation once all specialisations are known.
953 if (CS.getFunction() == F)
954 continue;
955 const unsigned Index = It->second;
956 AllSpecs[Index].CallSites.push_back(&CS);
957 } else {
958 // Calculate the specialisation gain.
960 unsigned Score = 0;
961 InstCostVisitor Visitor = getInstCostVisitorFor(F);
962 for (ArgInfo &A : S.Args) {
963 CodeSize += Visitor.getCodeSizeSavingsForArg(A.Formal, A.Actual);
964 Score += getInliningBonus(A.Formal, A.Actual);
965 }
967
968 unsigned CodeSizeSavings = getCostValue(CodeSize);
969 unsigned SpecSize = FuncSize - CodeSizeSavings;
970
971 auto IsProfitable = [&]() -> bool {
972 // No check required.
974 return true;
975
977 dbgs() << "FnSpecialization: Specialization bonus {Inlining = "
978 << Score << " (" << (Score * 100 / FuncSize) << "%)}\n");
979
980 // Minimum inlining bonus.
981 if (Score > MinInliningBonus * FuncSize / 100)
982 return true;
983
985 dbgs() << "FnSpecialization: Specialization bonus {CodeSize = "
986 << CodeSizeSavings << " ("
987 << (CodeSizeSavings * 100 / FuncSize) << "%)}\n");
988
989 // Minimum codesize savings.
990 if (CodeSizeSavings < MinCodeSizeSavings * FuncSize / 100)
991 return false;
992
993 // Lazily compute the Latency, to avoid unnecessarily computing BFI.
994 unsigned LatencySavings =
996
998 dbgs() << "FnSpecialization: Specialization bonus {Latency = "
999 << LatencySavings << " ("
1000 << (LatencySavings * 100 / FuncSize) << "%)}\n");
1001
1002 // Minimum latency savings.
1003 if (LatencySavings < MinLatencySavings * FuncSize / 100)
1004 return false;
1005 // Maximum codesize growth.
1006 if ((FunctionGrowth[F] + SpecSize) / FuncSize > MaxCodeSizeGrowth)
1007 return false;
1008
1009 Score += std::max(CodeSizeSavings, LatencySavings);
1010 return true;
1011 };
1012
1013 // Discard unprofitable specialisations.
1014 if (!IsProfitable())
1015 continue;
1016
1017 // Create a new specialisation entry.
1018 auto &Spec = AllSpecs.emplace_back(F, S, Score, SpecSize);
1019 if (CS.getFunction() != F)
1020 Spec.CallSites.push_back(&CS);
1021 const unsigned Index = AllSpecs.size() - 1;
1022 UniqueSpecs[S] = Index;
1023 if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted)
1024 It->second.second = Index + 1;
1025 }
1026 }
1027
1028 return !UniqueSpecs.empty();
1029}
1030
1031bool FunctionSpecializer::isCandidateFunction(Function *F) {
1032 if (F->isDeclaration() || F->arg_empty())
1033 return false;
1034
1035 if (F->isInterposable())
1036 return false;
1037
1038 if (F->hasFnAttribute(Attribute::NoDuplicate))
1039 return false;
1040
1041 if (F->hasOptSize())
1042 return false;
1043
1044 // Do not specialize the cloned function again.
1045 if (Specializations.contains(F))
1046 return false;
1047
1048 // If we're optimizing the function for size, we shouldn't specialize it.
1049 if (shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
1050 return false;
1051
1052 // Exit if the function is not executable. There's no point in specializing
1053 // a dead function.
1054 if (!Solver.isBlockExecutable(&F->getEntryBlock()))
1055 return false;
1056
1057 // It wastes time to specialize a function which would get inlined finally.
1058 if (F->hasFnAttribute(Attribute::AlwaysInline))
1059 return false;
1060
1061 LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
1062 << "\n");
1063 return true;
1064}
1065
1066Function *FunctionSpecializer::createSpecialization(Function *F,
1067 const SpecSig &S) {
1068 Function *Clone = cloneCandidateFunction(F, Specializations.size() + 1);
1069
1070 // The original function does not neccessarily have internal linkage, but the
1071 // clone must.
1073
1074 if (F->getEntryCount())
1075 Clone->setEntryCount(0);
1076
1077 // Initialize the lattice state of the arguments of the function clone,
1078 // marking the argument on which we specialized the function constant
1079 // with the given value.
1080 Solver.setLatticeValueForSpecializationArguments(Clone, S.Args);
1081 Solver.markBlockExecutable(&Clone->front());
1082 Solver.addArgumentTrackedFunction(Clone);
1083 Solver.addTrackedFunction(Clone);
1084
1085 // Mark all the specialized functions
1086 Specializations.insert(Clone);
1087 ++NumSpecsCreated;
1088
1089 return Clone;
1090}
1091
1092/// Compute the inlining bonus for replacing argument \p A with constant \p C.
1093/// The below heuristic is only concerned with exposing inlining
1094/// opportunities via indirect call promotion. If the argument is not a
1095/// (potentially casted) function pointer, give up.
1096unsigned FunctionSpecializer::getInliningBonus(Argument *A, Constant *C) {
1097 Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts());
1098 if (!CalledFunction)
1099 return 0;
1100
1101 // Get TTI for the called function (used for the inline cost).
1102 auto &CalleeTTI = (GetTTI)(*CalledFunction);
1103
1104 // Look at all the call sites whose called value is the argument.
1105 // Specializing the function on the argument would allow these indirect
1106 // calls to be promoted to direct calls. If the indirect call promotion
1107 // would likely enable the called function to be inlined, specializing is a
1108 // good idea.
1109 int InliningBonus = 0;
1110 for (User *U : A->users()) {
1111 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
1112 continue;
1113 auto *CS = cast<CallBase>(U);
1114 if (CS->getCalledOperand() != A)
1115 continue;
1116 if (CS->getFunctionType() != CalledFunction->getFunctionType())
1117 continue;
1118
1119 // Get the cost of inlining the called function at this call site. Note
1120 // that this is only an estimate. The called function may eventually
1121 // change in a way that leads to it not being inlined here, even though
1122 // inlining looks profitable now. For example, one of its called
1123 // functions may be inlined into it, making the called function too large
1124 // to be inlined into this call site.
1125 //
1126 // We apply a boost for performing indirect call promotion by increasing
1127 // the default threshold by the threshold for indirect calls.
1128 auto Params = getInlineParams();
1129 Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
1130 InlineCost IC =
1131 getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
1132
1133 // We clamp the bonus for this call to be between zero and the default
1134 // threshold.
1135 if (IC.isAlways())
1136 InliningBonus += Params.DefaultThreshold;
1137 else if (IC.isVariable() && IC.getCostDelta() > 0)
1138 InliningBonus += IC.getCostDelta();
1139
1140 LLVM_DEBUG(dbgs() << "FnSpecialization: Inlining bonus " << InliningBonus
1141 << " for user " << *U << "\n");
1142 }
1143
1144 return InliningBonus > 0 ? static_cast<unsigned>(InliningBonus) : 0;
1145}
1146
1147/// Determine if it is possible to specialise the function for constant values
1148/// of the formal parameter \p A.
1149bool FunctionSpecializer::isArgumentInteresting(Argument *A) {
1150 // No point in specialization if the argument is unused.
1151 if (A->user_empty())
1152 return false;
1153
1154 Type *Ty = A->getType();
1155 if (!Ty->isPointerTy() && (!SpecializeLiteralConstant ||
1156 (!Ty->isIntegerTy() && !Ty->isFloatingPointTy() && !Ty->isStructTy())))
1157 return false;
1158
1159 // SCCP solver does not record an argument that will be constructed on
1160 // stack.
1161 if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory())
1162 return false;
1163
1164 // For non-argument-tracked functions every argument is overdefined.
1165 if (!Solver.isArgumentTrackedFunction(A->getParent()))
1166 return true;
1167
1168 // Check the lattice value and decide if we should attemt to specialize,
1169 // based on this argument. No point in specialization, if the lattice value
1170 // is already a constant.
1171 bool IsOverdefined = Ty->isStructTy()
1172 ? any_of(Solver.getStructLatticeValueFor(A), SCCPSolver::isOverdefined)
1173 : SCCPSolver::isOverdefined(Solver.getLatticeValueFor(A));
1174
1175 LLVM_DEBUG(
1176 if (IsOverdefined)
1177 dbgs() << "FnSpecialization: Found interesting parameter "
1178 << A->getNameOrAsOperand() << "\n";
1179 else
1180 dbgs() << "FnSpecialization: Nothing to do, parameter "
1181 << A->getNameOrAsOperand() << " is already constant\n";
1182 );
1183 return IsOverdefined;
1184}
1185
1186/// Check if the value \p V (an actual argument) is a constant or can only
1187/// have a constant value. Return that constant.
1188Constant *FunctionSpecializer::getCandidateConstant(Value *V) {
1189 if (isa<PoisonValue>(V))
1190 return nullptr;
1191
1192 // Select for possible specialisation values that are constants or
1193 // are deduced to be constants or constant ranges with a single element.
1195 if (!C)
1196 C = Solver.getConstantOrNull(V);
1197
1198 // Don't specialize on (anything derived from) the address of a non-constant
1199 // global variable, unless explicitly enabled.
1200 if (C && C->getType()->isPointerTy() && !C->isNullValue())
1202 GV && !(GV->isConstant() || SpecializeOnAddress))
1203 return nullptr;
1204
1205 return C;
1206}
1207
1208void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin,
1209 const Spec *End) {
1210 // Collect the call sites that need updating.
1211 SmallVector<CallBase *> ToUpdate;
1212 for (User *U : F->users())
1213 if (auto *CS = dyn_cast<CallBase>(U);
1214 CS && CS->getCalledFunction() == F &&
1215 Solver.isBlockExecutable(CS->getParent()))
1216 ToUpdate.push_back(CS);
1217
1218 unsigned NCallsLeft = ToUpdate.size();
1219 for (CallBase *CS : ToUpdate) {
1220 bool ShouldDecrementCount = CS->getFunction() == F;
1221
1222 // Find the best matching specialisation.
1223 const Spec *BestSpec = nullptr;
1224 for (const Spec &S : make_range(Begin, End)) {
1225 if (!S.Clone || (BestSpec && S.Score <= BestSpec->Score))
1226 continue;
1227
1228 if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) {
1229 unsigned ArgNo = Arg.Formal->getArgNo();
1230 return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual;
1231 }))
1232 continue;
1233
1234 BestSpec = &S;
1235 }
1236
1237 if (BestSpec) {
1238 LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS
1239 << " to call " << BestSpec->Clone->getName() << "\n");
1240 CS->setCalledFunction(BestSpec->Clone);
1241 ShouldDecrementCount = true;
1242 }
1243
1244 if (ShouldDecrementCount)
1245 --NCallsLeft;
1246 }
1247
1248 // If the function has been completely specialized, the original function
1249 // is no longer needed. Mark it unreachable.
1250 // NOTE: If the address of a function is taken, we cannot treat it as dead
1251 // function.
1252 if (NCallsLeft == 0 && Solver.isArgumentTrackedFunction(F) &&
1253 !F->hasAddressTaken()) {
1254 Solver.markFunctionUnreachable(F);
1255 DeadFunctions.insert(F);
1256 }
1257}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static Function * cloneCandidateFunction(Function *F, unsigned NSpecs)
Clone the function F and remove the ssa_copy intrinsics added by the SCCPSolver in the cloned version...
static void removeSSACopy(Function &F)
static unsigned getCostValue(const Cost &C)
Get the unsigned Value of given Cost object.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Trace Metrics
FunctionAnalysisManager FAM
SI Fold Operands
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool onlyReadsMemory(unsigned OpNo) const
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned getArgOperandNo(const Use *U) const
Given a use for a arg operand, get the arg operand number that corresponds to it.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Conditional Branch instruction.
This is an important base class in LLVM.
Definition Constant.h:43
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:251
bool empty() const
Definition DenseMap.h:199
iterator end()
Definition DenseMap.h:169
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:242
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:312
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
This class represents a freeze function that returns random concrete value if an operand is either a ...
LLVM_ABI bool run()
Attempt to specialize functions in the module to enable constant propagation across function boundari...
InstCostVisitor getInstCostVisitorFor(Function *F)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
const BasicBlock & front() const
Definition Function.h:845
std::optional< uint64_t > getEntryCount() const
Get the entry count for this function.
void setEntryCount(uint64_t Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
void setLinkage(LinkageTypes LT)
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
bool isAlways() const
Definition InlineCost.h:140
int getCostDelta() const
Get the cost delta from the threshold for inlining.
Definition InlineCost.h:176
bool isVariable() const
Definition InlineCost.h:142
LLVM_ABI Cost getLatencySavingsForKnownConstants()
Compute the latency savings from replacing all arguments with constants for a specialization candidat...
LLVM_ABI Cost getCodeSizeSavingsForArg(Argument *A, Constant *C)
Compute the codesize savings for replacing argument A with constant C.
LLVM_ABI Cost getCodeSizeSavingsFromPendingPHIs()
bool isBlockExecutable(BasicBlock *BB) const
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
An instruction for reading from memory.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static LLVM_ABI bool isOverdefined(const ValueLatticeElement &LV)
This class represents the LLVM 'select' instruction.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Multiway switch.
@ TCK_CodeSize
Instruction code size.
@ TCK_Latency
The latency of instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI Constant * getCompare(CmpInst::Predicate Pred, Type *Ty, const ValueLatticeElement &Other, const DataLayout &DL) const
true, false or undef constants, or nullptr if the comparison cannot be evaluated.
static ValueLatticeElement get(Constant *C)
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI std::string getNameOrAsOperand() const
Definition Value.cpp:461
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
const int IndirectCallThreshold
Definition InlineCost.h:50
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
static cl::opt< unsigned > MinCodeSizeSavings("funcspec-min-codesize-savings", cl::init(20), cl::Hidden, cl::desc("Reject specializations whose codesize savings are less than this " "much percent of the original function size"))
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
hash_code hash_value(const FixedPointSemantics &Val)
static cl::opt< bool > SpecializeOnAddress("funcspec-on-address", cl::init(false), cl::Hidden, cl::desc("Enable function specialization on the address of global values"))
InstructionCost Cost
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Store
The extracted value is stored (ExtractElement only).
static cl::opt< unsigned > MaxIncomingPhiValues("funcspec-max-incoming-phi-values", cl::init(8), cl::Hidden, cl::desc("The maximum number of incoming values a PHI node can have to be " "considered during the specialization bonus estimation"))
static cl::opt< bool > SpecializeLiteralConstant("funcspec-for-literal-constant", cl::init(true), cl::Hidden, cl::desc("Enable specialization of functions that take a literal constant as an " "argument"))
DenseMap< Function *, std::pair< unsigned, unsigned > > SpecMap
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
static cl::opt< unsigned > MaxCodeSizeGrowth("funcspec-max-codesize-growth", cl::init(3), cl::Hidden, cl::desc("Maximum codesize growth allowed per function"))
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
static cl::opt< unsigned > MinLatencySavings("funcspec-min-latency-savings", cl::init(20), cl::Hidden, cl::desc("Reject specializations whose latency savings are less than this " "much percent of the original function size"))
LLVM_ABI Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F, const TargetLibraryInfo *TLI=nullptr)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
static cl::opt< unsigned > MinFunctionSize("funcspec-min-function-size", cl::init(500), cl::Hidden, cl::desc("Don't specialize functions that have less than this number of " "instructions"))
static cl::opt< unsigned > MaxDiscoveryIterations("funcspec-max-discovery-iterations", cl::init(100), cl::Hidden, cl::desc("The maximum number of iterations allowed " "when searching for transitive " "phis"))
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< const TargetLibraryInfo &(Function &)> GetTLI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr, function_ref< EphemeralValuesCache &(Function &)> GetEphValuesCache=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
@ Other
Any other memory.
Definition ModRef.h:68
static cl::opt< unsigned > MaxClones("funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc("The maximum number of clones allowed for a single function " "specialization"))
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
static cl::opt< bool > ForceSpecialization("force-specialization", cl::init(false), cl::Hidden, cl::desc("Force function specialization for every call site with a constant " "argument"))
static cl::opt< unsigned > MaxBlockPredecessors("funcspec-max-block-predecessors", cl::init(2), cl::Hidden, cl::desc("The maximum number of predecessors a basic block can have to be " "considered during the estimation of dead code"))
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
static cl::opt< unsigned > MinInliningBonus("funcspec-min-inlining-bonus", cl::init(300), cl::Hidden, cl::desc("Reject specializations whose inlining bonus is less than this " "much percent of the original function size"))
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
Helper struct shared between Function Specialization and SCCP Solver.
Definition SCCPSolver.h:42
Argument * Formal
Definition SCCPSolver.h:43
Constant * Actual
Definition SCCPSolver.h:44
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition CodeMetrics.h:34
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
static unsigned getHashValue(const SpecSig &S)
static bool isEqual(const SpecSig &LHS, const SpecSig &RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
SmallVector< ArgInfo, 4 > Args
SmallVector< CallBase * > CallSites