LLVM 22.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#include <cmath>
24
25using namespace llvm;
26
27#define DEBUG_TYPE "function-specialization"
28
29STATISTIC(NumSpecsCreated, "Number of specializations created");
30
32 "force-specialization", cl::init(false), cl::Hidden, cl::desc(
33 "Force function specialization for every call site with a constant "
34 "argument"));
35
37 "funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc(
38 "The maximum number of clones allowed for a single function "
39 "specialization"));
40
42 MaxDiscoveryIterations("funcspec-max-discovery-iterations", cl::init(100),
44 cl::desc("The maximum number of iterations allowed "
45 "when searching for transitive "
46 "phis"));
47
49 "funcspec-max-incoming-phi-values", cl::init(8), cl::Hidden,
50 cl::desc("The maximum number of incoming values a PHI node can have to be "
51 "considered during the specialization bonus estimation"));
52
54 "funcspec-max-block-predecessors", cl::init(2), cl::Hidden, cl::desc(
55 "The maximum number of predecessors a basic block can have to be "
56 "considered during the estimation of dead code"));
57
59 "funcspec-min-function-size", cl::init(500), cl::Hidden,
60 cl::desc("Don't specialize functions that have less than this number of "
61 "instructions"));
62
64 "funcspec-max-codesize-growth", cl::init(3), cl::Hidden, cl::desc(
65 "Maximum codesize growth allowed per function"));
66
68 "funcspec-min-codesize-savings", cl::init(20), cl::Hidden,
69 cl::desc("Reject specializations whose codesize savings are less than this "
70 "much percent of the original function size"));
71
73 "funcspec-min-latency-savings", cl::init(20), cl::Hidden,
74 cl::desc("Reject specializations whose latency savings are less than this "
75 "much percent of the original function size"));
76
78 "funcspec-min-inlining-bonus", cl::init(300), cl::Hidden,
79 cl::desc("Reject specializations whose inlining bonus is less than this "
80 "much percent of the original function size"));
81
83 "funcspec-on-address", cl::init(false), cl::Hidden, cl::desc(
84 "Enable function specialization on the address of global values"));
85
87 "funcspec-for-literal-constant", cl::init(true), cl::Hidden,
89 "Enable specialization of functions that take a literal constant as an "
90 "argument"));
91
92bool InstCostVisitor::canEliminateSuccessor(BasicBlock *BB,
93 BasicBlock *Succ) const {
94 unsigned I = 0;
95 return all_of(predecessors(Succ), [&I, BB, Succ, this](BasicBlock *Pred) {
96 return I++ < MaxBlockPredecessors &&
97 (Pred == BB || Pred == Succ || !isBlockExecutable(Pred));
98 });
99}
100
101// Estimates the codesize savings due to dead code after constant propagation.
102// \p WorkList represents the basic blocks of a specialization which will
103// eventually become dead once we replace instructions that are known to be
104// constants. The successors of such blocks are added to the list as long as
105// the \p Solver found they were executable prior to specialization, and only
106// if all their predecessors are dead.
107Cost InstCostVisitor::estimateBasicBlocks(
109 Cost CodeSize = 0;
110 // Accumulate the codesize savings of each basic block.
111 while (!WorkList.empty()) {
112 BasicBlock *BB = WorkList.pop_back_val();
113
114 // These blocks are considered dead as far as the InstCostVisitor
115 // is concerned. They haven't been proven dead yet by the Solver,
116 // but may become if we propagate the specialization arguments.
117 assert(Solver.isBlockExecutable(BB) && "BB already found dead by IPSCCP!");
118 if (!DeadBlocks.insert(BB).second)
119 continue;
120
121 for (Instruction &I : *BB) {
122 // If it's a known constant we have already accounted for it.
123 if (KnownConstants.contains(&I))
124 continue;
125
127
128 LLVM_DEBUG(dbgs() << "FnSpecialization: CodeSize " << C
129 << " for user " << I << "\n");
130 CodeSize += C;
131 }
132
133 // Keep adding dead successors to the list as long as they are
134 // executable and only reachable from dead blocks.
135 for (BasicBlock *SuccBB : successors(BB))
136 if (isBlockExecutable(SuccBB) && canEliminateSuccessor(BB, SuccBB))
137 WorkList.push_back(SuccBB);
138 }
139 return CodeSize;
140}
141
142Constant *InstCostVisitor::findConstantFor(Value *V) const {
143 if (auto *C = dyn_cast<Constant>(V))
144 return C;
145 if (auto *C = Solver.getConstantOrNull(V))
146 return C;
147 return KnownConstants.lookup(V);
148}
149
152 while (!PendingPHIs.empty()) {
153 Instruction *Phi = PendingPHIs.pop_back_val();
154 // The pending PHIs could have been proven dead by now.
155 if (isBlockExecutable(Phi->getParent()))
156 CodeSize += getCodeSizeSavingsForUser(Phi);
157 }
158 return CodeSize;
159}
160
161/// Compute the codesize savings for replacing argument \p A with constant \p C.
163 LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: "
164 << C->getNameOrAsOperand() << "\n");
166 for (auto *U : A->users())
167 if (auto *UI = dyn_cast<Instruction>(U))
168 if (isBlockExecutable(UI->getParent()))
169 CodeSize += getCodeSizeSavingsForUser(UI, A, C);
170
171 LLVM_DEBUG(dbgs() << "FnSpecialization: Accumulated bonus {CodeSize = "
172 << CodeSize << "} for argument " << *A << "\n");
173 return CodeSize;
174}
175
176/// Compute the latency savings from replacing all arguments with constants for
177/// a specialization candidate. As this function computes the latency savings
178/// for all Instructions in KnownConstants at once, it should be called only
179/// after every instruction has been visited, i.e. after:
180///
181/// * getCodeSizeSavingsForArg has been run for every constant argument of a
182/// specialization candidate
183///
184/// * getCodeSizeSavingsFromPendingPHIs has been run
185///
186/// to ensure that the latency savings are calculated for all Instructions we
187/// have visited and found to be constant.
189 auto &BFI = GetBFI(*F);
190 Cost TotalLatency = 0;
191
192 for (auto Pair : KnownConstants) {
193 Instruction *I = dyn_cast<Instruction>(Pair.first);
194 if (!I)
195 continue;
196
197 uint64_t Weight = BFI.getBlockFreq(I->getParent()).getFrequency() /
198 BFI.getEntryFreq().getFrequency();
199
200 Cost Latency =
202
203 LLVM_DEBUG(dbgs() << "FnSpecialization: {Latency = " << Latency
204 << "} for instruction " << *I << "\n");
205
206 TotalLatency += Latency;
207 }
208
209 return TotalLatency;
210}
211
212Cost InstCostVisitor::getCodeSizeSavingsForUser(Instruction *User, Value *Use,
213 Constant *C) {
214 // We have already propagated a constant for this user.
215 if (KnownConstants.contains(User))
216 return 0;
217
218 // Cache the iterator before visiting.
219 LastVisited = Use ? KnownConstants.insert({Use, C}).first
220 : KnownConstants.end();
221
222 Cost CodeSize = 0;
223 if (auto *I = dyn_cast<SwitchInst>(User)) {
224 CodeSize = estimateSwitchInst(*I);
225 } else if (auto *I = dyn_cast<BranchInst>(User)) {
226 CodeSize = estimateBranchInst(*I);
227 } else {
228 C = visit(*User);
229 if (!C)
230 return 0;
231 }
232
233 // Even though it doesn't make sense to bind switch and branch instructions
234 // with a constant, unlike any other instruction type, it prevents estimating
235 // their bonus multiple times.
236 KnownConstants.insert({User, C});
237
239
240 LLVM_DEBUG(dbgs() << "FnSpecialization: {CodeSize = " << CodeSize
241 << "} for user " << *User << "\n");
242
243 for (auto *U : User->users())
244 if (auto *UI = dyn_cast<Instruction>(U))
245 if (UI != User && isBlockExecutable(UI->getParent()))
246 CodeSize += getCodeSizeSavingsForUser(UI, User, C);
247
248 return CodeSize;
249}
250
251Cost InstCostVisitor::estimateSwitchInst(SwitchInst &I) {
252 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
253
254 if (I.getCondition() != LastVisited->first)
255 return 0;
256
257 auto *C = dyn_cast<ConstantInt>(LastVisited->second);
258 if (!C)
259 return 0;
260
261 BasicBlock *Succ = I.findCaseValue(C)->getCaseSuccessor();
262 // Initialize the worklist with the dead basic blocks. These are the
263 // destination labels which are different from the one corresponding
264 // to \p C. They should be executable and have a unique predecessor.
266 for (const auto &Case : I.cases()) {
267 BasicBlock *BB = Case.getCaseSuccessor();
268 if (BB != Succ && isBlockExecutable(BB) &&
269 canEliminateSuccessor(I.getParent(), BB))
270 WorkList.push_back(BB);
271 }
272
273 return estimateBasicBlocks(WorkList);
274}
275
276Cost InstCostVisitor::estimateBranchInst(BranchInst &I) {
277 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
278
279 if (I.getCondition() != LastVisited->first)
280 return 0;
281
282 BasicBlock *Succ = I.getSuccessor(LastVisited->second->isOneValue());
283 // Initialize the worklist with the dead successor as long as
284 // it is executable and has a unique predecessor.
286 if (isBlockExecutable(Succ) && canEliminateSuccessor(I.getParent(), Succ))
287 WorkList.push_back(Succ);
288
289 return estimateBasicBlocks(WorkList);
290}
291
292bool InstCostVisitor::discoverTransitivelyIncomingValues(
293 Constant *Const, PHINode *Root, DenseSet<PHINode *> &TransitivePHIs) {
294
296 WorkList.push_back(Root);
297 unsigned Iter = 0;
298
299 while (!WorkList.empty()) {
300 PHINode *PN = WorkList.pop_back_val();
301
302 if (++Iter > MaxDiscoveryIterations ||
304 return false;
305
306 if (!TransitivePHIs.insert(PN).second)
307 continue;
308
309 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
310 Value *V = PN->getIncomingValue(I);
311
312 // Disregard self-references and dead incoming values.
313 if (auto *Inst = dyn_cast<Instruction>(V))
314 if (Inst == PN || !isBlockExecutable(PN->getIncomingBlock(I)))
315 continue;
316
317 if (Constant *C = findConstantFor(V)) {
318 // Not all incoming values are the same constant. Bail immediately.
319 if (C != Const)
320 return false;
321 continue;
322 }
323
324 if (auto *Phi = dyn_cast<PHINode>(V)) {
325 WorkList.push_back(Phi);
326 continue;
327 }
328
329 // We can't reason about anything else.
330 return false;
331 }
332 }
333 return true;
334}
335
336Constant *InstCostVisitor::visitPHINode(PHINode &I) {
337 if (I.getNumIncomingValues() > MaxIncomingPhiValues)
338 return nullptr;
339
340 bool Inserted = VisitedPHIs.insert(&I).second;
341 Constant *Const = nullptr;
342 bool HaveSeenIncomingPHI = false;
343
344 for (unsigned Idx = 0, E = I.getNumIncomingValues(); Idx != E; ++Idx) {
345 Value *V = I.getIncomingValue(Idx);
346
347 // Disregard self-references and dead incoming values.
348 if (auto *Inst = dyn_cast<Instruction>(V))
349 if (Inst == &I || !isBlockExecutable(I.getIncomingBlock(Idx)))
350 continue;
351
352 if (Constant *C = findConstantFor(V)) {
353 if (!Const)
354 Const = C;
355 // Not all incoming values are the same constant. Bail immediately.
356 if (C != Const)
357 return nullptr;
358 continue;
359 }
360
361 if (Inserted) {
362 // First time we are seeing this phi. We will retry later, after
363 // all the constant arguments have been propagated. Bail for now.
364 PendingPHIs.push_back(&I);
365 return nullptr;
366 }
367
368 if (isa<PHINode>(V)) {
369 // Perhaps it is a Transitive Phi. We will confirm later.
370 HaveSeenIncomingPHI = true;
371 continue;
372 }
373
374 // We can't reason about anything else.
375 return nullptr;
376 }
377
378 if (!Const)
379 return nullptr;
380
381 if (!HaveSeenIncomingPHI)
382 return Const;
383
384 DenseSet<PHINode *> TransitivePHIs;
385 if (!discoverTransitivelyIncomingValues(Const, &I, TransitivePHIs))
386 return nullptr;
387
388 return Const;
389}
390
391Constant *InstCostVisitor::visitFreezeInst(FreezeInst &I) {
392 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
393
394 if (isGuaranteedNotToBeUndefOrPoison(LastVisited->second))
395 return LastVisited->second;
396 return nullptr;
397}
398
399Constant *InstCostVisitor::visitCallBase(CallBase &I) {
400 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
401
402 Function *F = I.getCalledFunction();
403 if (!F || !canConstantFoldCallTo(&I, F))
404 return nullptr;
405
407 Operands.reserve(I.getNumOperands());
408
409 for (unsigned Idx = 0, E = I.getNumOperands() - 1; Idx != E; ++Idx) {
410 Value *V = I.getOperand(Idx);
411 if (isa<MetadataAsValue>(V))
412 return nullptr;
413 Constant *C = findConstantFor(V);
414 if (!C)
415 return nullptr;
416 Operands.push_back(C);
417 }
418
419 auto Ops = ArrayRef(Operands.begin(), Operands.end());
420 return ConstantFoldCall(&I, F, Ops);
421}
422
423Constant *InstCostVisitor::visitLoadInst(LoadInst &I) {
424 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
425
426 if (isa<ConstantPointerNull>(LastVisited->second))
427 return nullptr;
428 return ConstantFoldLoadFromConstPtr(LastVisited->second, I.getType(), DL);
429}
430
431Constant *InstCostVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
433 Operands.reserve(I.getNumOperands());
434
435 for (unsigned Idx = 0, E = I.getNumOperands(); Idx != E; ++Idx) {
436 Value *V = I.getOperand(Idx);
437 Constant *C = findConstantFor(V);
438 if (!C)
439 return nullptr;
440 Operands.push_back(C);
441 }
442
443 auto Ops = ArrayRef(Operands.begin(), Operands.end());
444 return ConstantFoldInstOperands(&I, Ops, DL);
445}
446
447Constant *InstCostVisitor::visitSelectInst(SelectInst &I) {
448 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
449
450 if (I.getCondition() == LastVisited->first) {
451 Value *V = LastVisited->second->isZeroValue() ? I.getFalseValue()
452 : I.getTrueValue();
453 return findConstantFor(V);
454 }
455 if (Constant *Condition = findConstantFor(I.getCondition()))
456 if ((I.getTrueValue() == LastVisited->first && Condition->isOneValue()) ||
457 (I.getFalseValue() == LastVisited->first && Condition->isZeroValue()))
458 return LastVisited->second;
459 return nullptr;
460}
461
462Constant *InstCostVisitor::visitCastInst(CastInst &I) {
463 return ConstantFoldCastOperand(I.getOpcode(), LastVisited->second,
464 I.getType(), DL);
465}
466
467Constant *InstCostVisitor::visitCmpInst(CmpInst &I) {
468 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
469
470 Constant *Const = LastVisited->second;
471 bool ConstOnRHS = I.getOperand(1) == LastVisited->first;
472 Value *V = ConstOnRHS ? I.getOperand(0) : I.getOperand(1);
473 Constant *Other = findConstantFor(V);
474
475 if (Other) {
476 if (ConstOnRHS)
477 std::swap(Const, Other);
478 return ConstantFoldCompareInstOperands(I.getPredicate(), Const, Other, DL);
479 }
480
481 // If we haven't found Other to be a specific constant value, we may still be
482 // able to constant fold using information from the lattice value.
483 const ValueLatticeElement &ConstLV = ValueLatticeElement::get(Const);
484 const ValueLatticeElement &OtherLV = Solver.getLatticeValueFor(V);
485 auto &V1State = ConstOnRHS ? OtherLV : ConstLV;
486 auto &V2State = ConstOnRHS ? ConstLV : OtherLV;
487 return V1State.getCompare(I.getPredicate(), I.getType(), V2State, DL);
488}
489
490Constant *InstCostVisitor::visitUnaryOperator(UnaryOperator &I) {
491 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
492
493 return ConstantFoldUnaryOpOperand(I.getOpcode(), LastVisited->second, DL);
494}
495
496Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) {
497 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
498
499 bool ConstOnRHS = I.getOperand(1) == LastVisited->first;
500 Value *V = ConstOnRHS ? I.getOperand(0) : I.getOperand(1);
501 Constant *Other = findConstantFor(V);
502 Value *OtherVal = Other ? Other : V;
503 Value *ConstVal = LastVisited->second;
504
505 if (ConstOnRHS)
506 std::swap(ConstVal, OtherVal);
507
508 return dyn_cast_or_null<Constant>(
509 simplifyBinOp(I.getOpcode(), ConstVal, OtherVal, SimplifyQuery(DL)));
510}
511
512Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca,
513 CallInst *Call) {
514 Value *StoreValue = nullptr;
515 for (auto *User : Alloca->users()) {
516 // We can't use llvm::isAllocaPromotable() as that would fail because of
517 // the usage in the CallInst, which is what we check here.
518 if (User == Call)
519 continue;
520
521 if (auto *Store = dyn_cast<StoreInst>(User)) {
522 // This is a duplicate store, bail out.
523 if (StoreValue || Store->isVolatile())
524 return nullptr;
525 StoreValue = Store->getValueOperand();
526 continue;
527 }
528 // Bail if there is any other unknown usage.
529 return nullptr;
530 }
531
532 if (!StoreValue)
533 return nullptr;
534
535 return getCandidateConstant(StoreValue);
536}
537
538// A constant stack value is an AllocaInst that has a single constant
539// value stored to it. Return this constant if such an alloca stack value
540// is a function argument.
541Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call,
542 Value *Val) {
543 if (!Val)
544 return nullptr;
545 Val = Val->stripPointerCasts();
546 if (auto *ConstVal = dyn_cast<ConstantInt>(Val))
547 return ConstVal;
548 auto *Alloca = dyn_cast<AllocaInst>(Val);
549 if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())
550 return nullptr;
551 return getPromotableAlloca(Alloca, Call);
552}
553
554// To support specializing recursive functions, it is important to propagate
555// constant arguments because after a first iteration of specialisation, a
556// reduced example may look like this:
557//
558// define internal void @RecursiveFn(i32* arg1) {
559// %temp = alloca i32, align 4
560// store i32 2 i32* %temp, align 4
561// call void @RecursiveFn.1(i32* nonnull %temp)
562// ret void
563// }
564//
565// Before a next iteration, we need to propagate the constant like so
566// which allows further specialization in next iterations.
567//
568// @funcspec.arg = internal constant i32 2
569//
570// define internal void @someFunc(i32* arg1) {
571// call void @otherFunc(i32* nonnull @funcspec.arg)
572// ret void
573// }
574//
575// See if there are any new constant values for the callers of \p F via
576// stack variables and promote them to global variables.
577void FunctionSpecializer::promoteConstantStackValues(Function *F) {
578 for (User *U : F->users()) {
579
580 auto *Call = dyn_cast<CallInst>(U);
581 if (!Call)
582 continue;
583
584 if (!Solver.isBlockExecutable(Call->getParent()))
585 continue;
586
587 for (const Use &U : Call->args()) {
588 unsigned Idx = Call->getArgOperandNo(&U);
589 Value *ArgOp = Call->getArgOperand(Idx);
590 Type *ArgOpType = ArgOp->getType();
591
592 if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy())
593 continue;
594
595 auto *ConstVal = getConstantStackValue(Call, ArgOp);
596 if (!ConstVal)
597 continue;
598
599 Value *GV = new GlobalVariable(M, ConstVal->getType(), true,
601 "specialized.arg." + Twine(++NGlobals));
602 Call->setArgOperand(Idx, GV);
603 }
604 }
605}
606
607// The SCCP solver inserts bitcasts for PredicateInfo. These interfere with the
608// promoteConstantStackValues() optimization.
609static void removeSSACopy(Function &F) {
610 for (BasicBlock &BB : F) {
611 for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
612 auto *BC = dyn_cast<BitCastInst>(&Inst);
613 if (!BC || BC->getType() != BC->getOperand(0)->getType())
614 continue;
615 Inst.replaceAllUsesWith(BC->getOperand(0));
616 Inst.eraseFromParent();
617 }
618 }
619}
620
621/// Remove any ssa_copy intrinsics that may have been introduced.
622void FunctionSpecializer::cleanUpSSA() {
623 for (Function *F : Specializations)
625}
626
627
628template <> struct llvm::DenseMapInfo<SpecSig> {
629 static inline SpecSig getEmptyKey() { return {~0U, {}}; }
630
631 static inline SpecSig getTombstoneKey() { return {~1U, {}}; }
632
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 LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call
788 << " to call " << S.Clone->getName() << "\n");
789 Call->setCalledFunction(S.Clone);
790 }
791
792 Clones.push_back(S.Clone);
793 OriginalFuncs.insert(S.F);
794 }
795
796 Solver.solveWhileResolvedUndefsIn(Clones);
797
798 // Update the rest of the call sites - these are the recursive calls, calls
799 // to discarded specialisations and calls that may match a specialisation
800 // after the solver runs.
801 for (Function *F : OriginalFuncs) {
802 auto [Begin, End] = SM[F];
803 updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End);
804 }
805
806 for (Function *F : Clones) {
807 if (F->getReturnType()->isVoidTy())
808 continue;
809 if (F->getReturnType()->isStructTy()) {
810 auto *STy = cast<StructType>(F->getReturnType());
811 if (!Solver.isStructLatticeConstant(F, STy))
812 continue;
813 } else {
814 auto It = Solver.getTrackedRetVals().find(F);
815 assert(It != Solver.getTrackedRetVals().end() &&
816 "Return value ought to be tracked");
817 if (SCCPSolver::isOverdefined(It->second))
818 continue;
819 }
820 for (User *U : F->users()) {
821 if (auto *CS = dyn_cast<CallBase>(U)) {
822 //The user instruction does not call our function.
823 if (CS->getCalledFunction() != F)
824 continue;
825 Solver.resetLatticeValueFor(CS);
826 }
827 }
828 }
829
830 // Rerun the solver to notify the users of the modified callsites.
832
833 for (Function *F : OriginalFuncs)
834 if (FunctionMetrics[F].isRecursive)
835 promoteConstantStackValues(F);
836
837 return true;
838}
839
840void FunctionSpecializer::removeDeadFunctions() {
841 for (Function *F : DeadFunctions) {
842 LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function "
843 << F->getName() << "\n");
844 if (FAM)
845 FAM->clear(*F, F->getName());
846
847 // Remove all the callsites that were proven unreachable once, and replace
848 // them with poison.
849 for (User *U : make_early_inc_range(F->users())) {
850 assert((isa<CallInst>(U) || isa<InvokeInst>(U)) &&
851 "User of dead function must be call or invoke");
852 Instruction *CS = cast<Instruction>(U);
854 CS->eraseFromParent();
855 }
856 F->eraseFromParent();
857 }
858 DeadFunctions.clear();
859}
860
861/// Clone the function \p F and remove the ssa_copy intrinsics added by
862/// the SCCPSolver in the cloned version.
863static Function *cloneCandidateFunction(Function *F, unsigned NSpecs) {
864 ValueToValueMapTy Mappings;
865 Function *Clone = CloneFunction(F, Mappings);
866 Clone->setName(F->getName() + ".specialized." + Twine(NSpecs));
867 removeSSACopy(*Clone);
868 return Clone;
869}
870
871bool FunctionSpecializer::findSpecializations(Function *F, unsigned FuncSize,
872 SmallVectorImpl<Spec> &AllSpecs,
873 SpecMap &SM) {
874 // A mapping from a specialisation signature to the index of the respective
875 // entry in the all specialisation array. Used to ensure uniqueness of
876 // specialisations.
877 DenseMap<SpecSig, unsigned> UniqueSpecs;
878
879 // Get a list of interesting arguments.
881 for (Argument &Arg : F->args())
882 if (isArgumentInteresting(&Arg))
883 Args.push_back(&Arg);
884
885 if (Args.empty())
886 return false;
887
888 for (User *U : F->users()) {
889 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
890 continue;
891 auto &CS = *cast<CallBase>(U);
892
893 // The user instruction does not call our function.
894 if (CS.getCalledFunction() != F)
895 continue;
896
897 // If the call site has attribute minsize set, that callsite won't be
898 // specialized.
899 if (CS.hasFnAttr(Attribute::MinSize))
900 continue;
901
902 // If the parent of the call site will never be executed, we don't need
903 // to worry about the passed value.
904 if (!Solver.isBlockExecutable(CS.getParent()))
905 continue;
906
907 // Examine arguments and create a specialisation candidate from the
908 // constant operands of this call site.
909 SpecSig S;
910 for (Argument *A : Args) {
911 Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo()));
912 if (!C)
913 continue;
914 LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument "
915 << A->getName() << " : " << C->getNameOrAsOperand()
916 << "\n");
917 S.Args.push_back({A, C});
918 }
919
920 if (S.Args.empty())
921 continue;
922
923 // Check if we have encountered the same specialisation already.
924 if (auto It = UniqueSpecs.find(S); It != UniqueSpecs.end()) {
925 // Existing specialisation. Add the call to the list to rewrite, unless
926 // it's a recursive call. A specialisation, generated because of a
927 // recursive call may end up as not the best specialisation for all
928 // the cloned instances of this call, which result from specialising
929 // functions. Hence we don't rewrite the call directly, but match it with
930 // the best specialisation once all specialisations are known.
931 if (CS.getFunction() == F)
932 continue;
933 const unsigned Index = It->second;
934 AllSpecs[Index].CallSites.push_back(&CS);
935 } else {
936 // Calculate the specialisation gain.
938 unsigned Score = 0;
940 for (ArgInfo &A : S.Args) {
941 CodeSize += Visitor.getCodeSizeSavingsForArg(A.Formal, A.Actual);
942 Score += getInliningBonus(A.Formal, A.Actual);
943 }
945
946 unsigned CodeSizeSavings = getCostValue(CodeSize);
947 unsigned SpecSize = FuncSize - CodeSizeSavings;
948
949 auto IsProfitable = [&]() -> bool {
950 // No check required.
952 return true;
953
955 dbgs() << "FnSpecialization: Specialization bonus {Inlining = "
956 << Score << " (" << (Score * 100 / FuncSize) << "%)}\n");
957
958 // Minimum inlining bonus.
959 if (Score > MinInliningBonus * FuncSize / 100)
960 return true;
961
963 dbgs() << "FnSpecialization: Specialization bonus {CodeSize = "
964 << CodeSizeSavings << " ("
965 << (CodeSizeSavings * 100 / FuncSize) << "%)}\n");
966
967 // Minimum codesize savings.
968 if (CodeSizeSavings < MinCodeSizeSavings * FuncSize / 100)
969 return false;
970
971 // Lazily compute the Latency, to avoid unnecessarily computing BFI.
972 unsigned LatencySavings =
974
976 dbgs() << "FnSpecialization: Specialization bonus {Latency = "
977 << LatencySavings << " ("
978 << (LatencySavings * 100 / FuncSize) << "%)}\n");
979
980 // Minimum latency savings.
981 if (LatencySavings < MinLatencySavings * FuncSize / 100)
982 return false;
983 // Maximum codesize growth.
984 if ((FunctionGrowth[F] + SpecSize) / FuncSize > MaxCodeSizeGrowth)
985 return false;
986
987 Score += std::max(CodeSizeSavings, LatencySavings);
988 return true;
989 };
990
991 // Discard unprofitable specialisations.
992 if (!IsProfitable())
993 continue;
994
995 // Create a new specialisation entry.
996 auto &Spec = AllSpecs.emplace_back(F, S, Score, SpecSize);
997 if (CS.getFunction() != F)
998 Spec.CallSites.push_back(&CS);
999 const unsigned Index = AllSpecs.size() - 1;
1000 UniqueSpecs[S] = Index;
1001 if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted)
1002 It->second.second = Index + 1;
1003 }
1004 }
1005
1006 return !UniqueSpecs.empty();
1007}
1008
1009bool FunctionSpecializer::isCandidateFunction(Function *F) {
1010 if (F->isDeclaration() || F->arg_empty())
1011 return false;
1012
1013 if (F->hasFnAttribute(Attribute::NoDuplicate))
1014 return false;
1015
1016 // Do not specialize the cloned function again.
1017 if (Specializations.contains(F))
1018 return false;
1019
1020 // If we're optimizing the function for size, we shouldn't specialize it.
1021 if (shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
1022 return false;
1023
1024 // Exit if the function is not executable. There's no point in specializing
1025 // a dead function.
1026 if (!Solver.isBlockExecutable(&F->getEntryBlock()))
1027 return false;
1028
1029 // It wastes time to specialize a function which would get inlined finally.
1030 if (F->hasFnAttribute(Attribute::AlwaysInline))
1031 return false;
1032
1033 LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
1034 << "\n");
1035 return true;
1036}
1037
1038Function *FunctionSpecializer::createSpecialization(Function *F,
1039 const SpecSig &S) {
1040 Function *Clone = cloneCandidateFunction(F, Specializations.size() + 1);
1041
1042 // The original function does not neccessarily have internal linkage, but the
1043 // clone must.
1045
1046 // Initialize the lattice state of the arguments of the function clone,
1047 // marking the argument on which we specialized the function constant
1048 // with the given value.
1050 Solver.markBlockExecutable(&Clone->front());
1051 Solver.addArgumentTrackedFunction(Clone);
1052 Solver.addTrackedFunction(Clone);
1053
1054 // Mark all the specialized functions
1055 Specializations.insert(Clone);
1056 ++NumSpecsCreated;
1057
1058 return Clone;
1059}
1060
1061/// Compute the inlining bonus for replacing argument \p A with constant \p C.
1062/// The below heuristic is only concerned with exposing inlining
1063/// opportunities via indirect call promotion. If the argument is not a
1064/// (potentially casted) function pointer, give up.
1065unsigned FunctionSpecializer::getInliningBonus(Argument *A, Constant *C) {
1066 Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts());
1067 if (!CalledFunction)
1068 return 0;
1069
1070 // Get TTI for the called function (used for the inline cost).
1071 auto &CalleeTTI = (GetTTI)(*CalledFunction);
1072
1073 // Look at all the call sites whose called value is the argument.
1074 // Specializing the function on the argument would allow these indirect
1075 // calls to be promoted to direct calls. If the indirect call promotion
1076 // would likely enable the called function to be inlined, specializing is a
1077 // good idea.
1078 int InliningBonus = 0;
1079 for (User *U : A->users()) {
1080 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
1081 continue;
1082 auto *CS = cast<CallBase>(U);
1083 if (CS->getCalledOperand() != A)
1084 continue;
1085 if (CS->getFunctionType() != CalledFunction->getFunctionType())
1086 continue;
1087
1088 // Get the cost of inlining the called function at this call site. Note
1089 // that this is only an estimate. The called function may eventually
1090 // change in a way that leads to it not being inlined here, even though
1091 // inlining looks profitable now. For example, one of its called
1092 // functions may be inlined into it, making the called function too large
1093 // to be inlined into this call site.
1094 //
1095 // We apply a boost for performing indirect call promotion by increasing
1096 // the default threshold by the threshold for indirect calls.
1097 auto Params = getInlineParams();
1098 Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
1099 InlineCost IC =
1100 getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
1101
1102 // We clamp the bonus for this call to be between zero and the default
1103 // threshold.
1104 if (IC.isAlways())
1105 InliningBonus += Params.DefaultThreshold;
1106 else if (IC.isVariable() && IC.getCostDelta() > 0)
1107 InliningBonus += IC.getCostDelta();
1108
1109 LLVM_DEBUG(dbgs() << "FnSpecialization: Inlining bonus " << InliningBonus
1110 << " for user " << *U << "\n");
1111 }
1112
1113 return InliningBonus > 0 ? static_cast<unsigned>(InliningBonus) : 0;
1114}
1115
1116/// Determine if it is possible to specialise the function for constant values
1117/// of the formal parameter \p A.
1118bool FunctionSpecializer::isArgumentInteresting(Argument *A) {
1119 // No point in specialization if the argument is unused.
1120 if (A->user_empty())
1121 return false;
1122
1123 Type *Ty = A->getType();
1124 if (!Ty->isPointerTy() && (!SpecializeLiteralConstant ||
1125 (!Ty->isIntegerTy() && !Ty->isFloatingPointTy() && !Ty->isStructTy())))
1126 return false;
1127
1128 // SCCP solver does not record an argument that will be constructed on
1129 // stack.
1130 if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory())
1131 return false;
1132
1133 // For non-argument-tracked functions every argument is overdefined.
1134 if (!Solver.isArgumentTrackedFunction(A->getParent()))
1135 return true;
1136
1137 // Check the lattice value and decide if we should attemt to specialize,
1138 // based on this argument. No point in specialization, if the lattice value
1139 // is already a constant.
1140 bool IsOverdefined = Ty->isStructTy()
1142 : SCCPSolver::isOverdefined(Solver.getLatticeValueFor(A));
1143
1144 LLVM_DEBUG(
1145 if (IsOverdefined)
1146 dbgs() << "FnSpecialization: Found interesting parameter "
1147 << A->getNameOrAsOperand() << "\n";
1148 else
1149 dbgs() << "FnSpecialization: Nothing to do, parameter "
1150 << A->getNameOrAsOperand() << " is already constant\n";
1151 );
1152 return IsOverdefined;
1153}
1154
1155/// Check if the value \p V (an actual argument) is a constant or can only
1156/// have a constant value. Return that constant.
1157Constant *FunctionSpecializer::getCandidateConstant(Value *V) {
1158 if (isa<PoisonValue>(V))
1159 return nullptr;
1160
1161 // Select for possible specialisation values that are constants or
1162 // are deduced to be constants or constant ranges with a single element.
1163 Constant *C = dyn_cast<Constant>(V);
1164 if (!C)
1165 C = Solver.getConstantOrNull(V);
1166
1167 // Don't specialize on (anything derived from) the address of a non-constant
1168 // global variable, unless explicitly enabled.
1169 if (C && C->getType()->isPointerTy() && !C->isNullValue())
1170 if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C));
1171 GV && !(GV->isConstant() || SpecializeOnAddress))
1172 return nullptr;
1173
1174 return C;
1175}
1176
1177void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin,
1178 const Spec *End) {
1179 // Collect the call sites that need updating.
1180 SmallVector<CallBase *> ToUpdate;
1181 for (User *U : F->users())
1182 if (auto *CS = dyn_cast<CallBase>(U);
1183 CS && CS->getCalledFunction() == F &&
1184 Solver.isBlockExecutable(CS->getParent()))
1185 ToUpdate.push_back(CS);
1186
1187 unsigned NCallsLeft = ToUpdate.size();
1188 for (CallBase *CS : ToUpdate) {
1189 bool ShouldDecrementCount = CS->getFunction() == F;
1190
1191 // Find the best matching specialisation.
1192 const Spec *BestSpec = nullptr;
1193 for (const Spec &S : make_range(Begin, End)) {
1194 if (!S.Clone || (BestSpec && S.Score <= BestSpec->Score))
1195 continue;
1196
1197 if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) {
1198 unsigned ArgNo = Arg.Formal->getArgNo();
1199 return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual;
1200 }))
1201 continue;
1202
1203 BestSpec = &S;
1204 }
1205
1206 if (BestSpec) {
1207 LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS
1208 << " to call " << BestSpec->Clone->getName() << "\n");
1209 CS->setCalledFunction(BestSpec->Clone);
1210 ShouldDecrementCount = true;
1211 }
1212
1213 if (ShouldDecrementCount)
1214 --NCallsLeft;
1215 }
1216
1217 // If the function has been completely specialized, the original function
1218 // is no longer needed. Mark it unreachable.
1219 // NOTE: If the address of a function is taken, we cannot treat it as dead
1220 // function.
1221 if (NCallsLeft == 0 && Solver.isArgumentTrackedFunction(F) &&
1222 !F->hasAddressTaken()) {
1223 Solver.markFunctionUnreachable(F);
1224 DeadFunctions.insert(F);
1225 }
1226}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
bool End
Definition: ELF_riscv.cpp:480
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 > MaxDiscoveryIterations("funcspec-max-discovery-iterations", cl::init(100), cl::Hidden, cl::desc("The maximum number of iterations allowed " "when searching for transitive " "phis"))
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< 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"))
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 cl::opt< unsigned > MaxCodeSizeGrowth("funcspec-max-codesize-growth", cl::init(3), cl::Hidden, cl::desc("Maximum codesize growth allowed per function"))
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"))
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"))
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"))
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< 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"))
static cl::opt< bool > SpecializeOnAddress("funcspec-on-address", cl::init(false), cl::Hidden, cl::desc("Enable function specialization on the address of global values"))
static unsigned getCostValue(const Cost &C)
Get the unsigned Value of given Cost object.
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"))
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
Machine Trace Metrics
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:167
#define LLVM_DEBUG(...)
Definition: Debug.h:119
This pass exposes codegen information to IR-level passes.
Value * RHS
Value * LHS
an instruction to allocate memory on the stack
Definition: Instructions.h:64
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:121
void clear(IRUnitT &IR, llvm::StringRef Name)
Clear any cached analysis results for a single unit of IR.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
Conditional or Unconditional Branch instruction.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1116
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:448
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:666
This is an important base class in LLVM.
Definition: Constant.h:43
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:203
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:177
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition: DenseMap.h:245
bool empty() const
Definition: DenseMap.h:119
iterator end()
Definition: DenseMap.h:87
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:168
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:230
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
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:209
const BasicBlock & front() const
Definition: Function.h:858
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:949
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:539
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:60
Represents the cost of inlining a function.
Definition: InlineCost.h:91
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.
Definition: Instruction.cpp:82
An instruction for reading from memory.
Definition: Instructions.h:180
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:269
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.
Definition: Constants.cpp:1885
SCCPSolver - This interface class is a general purpose solver for Sparse Conditional Constant Propaga...
Definition: SCCPSolver.h:66
LLVM_ABI void resetLatticeValueFor(CallBase *Call)
Invalidate the Lattice Value of Call and its users after specializing the call.
LLVM_ABI bool isStructLatticeConstant(Function *F, StructType *STy)
LLVM_ABI void addTrackedFunction(Function *F)
addTrackedFunction - If the SCCP solver is supposed to track calls into and out of the specified func...
LLVM_ABI void solveWhileResolvedUndefsIn(Module &M)
LLVM_ABI void addArgumentTrackedFunction(Function *F)
LLVM_ABI void solveWhileResolvedUndefs()
LLVM_ABI std::vector< ValueLatticeElement > getStructLatticeValueFor(Value *V) const
LLVM_ABI Constant * getConstantOrNull(Value *V) const
Return either a Constant or nullptr for a given Value.
LLVM_ABI const ValueLatticeElement & getLatticeValueFor(Value *V) const
LLVM_ABI bool isBlockExecutable(BasicBlock *BB) const
LLVM_ABI bool markBlockExecutable(BasicBlock *BB)
markBlockExecutable - This method can be used by clients to mark all of the blocks that are known to ...
LLVM_ABI void setLatticeValueForSpecializationArguments(Function *F, const SmallVectorImpl< ArgInfo > &Args)
Set the Lattice Value for the arguments of a specialization F.
LLVM_ABI const MapVector< Function *, ValueLatticeElement > & getTrackedRetVals() const
getTrackedRetVals - Get the inferred return value map.
static LLVM_ABI bool isOverdefined(const ValueLatticeElement &LV)
Definition: SCCPSolver.cpp:57
LLVM_ABI void markFunctionUnreachable(Function *F)
Mark all of the blocks in function F non-executable.
LLVM_ABI bool isArgumentTrackedFunction(Function *F)
Returns true if the given function is in the solver's set of argument-tracked functions.
This class represents the LLVM 'select' instruction.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
Multiway switch.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_CodeSize
Instruction code size.
@ TCK_Latency
The latency of instruction.
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:267
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:261
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:240
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
This class represents lattice values for constants.
Definition: ValueLattice.h:27
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)
Definition: ValueLattice.h:201
LLVM Value Representation.
Definition: Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:390
LLVM_ABI std::string getNameOrAsOperand() const
Definition: Value.cpp:457
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:546
iterator_range< user_iterator > users()
Definition: Value.h:426
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:701
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:322
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:194
const ParentTy * getParent() const
Definition: ilist_node.h:34
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
const int IndirectCallThreshold
Definition: InlineCost.h:50
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:1744
hash_code hash_value(const FixedPointSemantics &Val)
Definition: APFixedPoint.h:137
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
auto successors(const MachineBasicBlock *BB)
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.
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:663
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...
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:1751
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:207
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
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.
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
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.
LLVM_ABI InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options.
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:858
#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).
Definition: CodeMetrics.cpp:71
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...
Definition: DenseMapInfo.h:54
SmallVector< ArgInfo, 4 > Args
SmallVector< CallBase * > CallSites