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