1 //===- FunctionSpecialization.cpp - Function Specialization ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This specialises functions with constant parameters. Constant parameters 10 // like function pointers and constant globals are propagated to the callee by 11 // specializing the function. The main benefit of this pass at the moment is 12 // that indirect calls are transformed into direct calls, which provides inline 13 // opportunities that the inliner would not have been able to achieve. That's 14 // why function specialisation is run before the inliner in the optimisation 15 // pipeline; that is by design. Otherwise, we would only benefit from constant 16 // passing, which is a valid use-case too, but hasn't been explored much in 17 // terms of performance uplifts, cost-model and compile-time impact. 18 // 19 // Current limitations: 20 // - It does not yet handle integer ranges. We do support "literal constants", 21 // but that's off by default under an option. 22 // - The cost-model could be further looked into (it mainly focuses on inlining 23 // benefits), 24 // 25 // Ideas: 26 // - With a function specialization attribute for arguments, we could have 27 // a direct way to steer function specialization, avoiding the cost-model, 28 // and thus control compile-times / code-size. 29 // 30 // Todos: 31 // - Specializing recursive functions relies on running the transformation a 32 // number of times, which is controlled by option 33 // `func-specialization-max-iters`. Thus, increasing this value and the 34 // number of iterations, will linearly increase the number of times recursive 35 // functions get specialized, see also the discussion in 36 // https://reviews.llvm.org/D106426 for details. Perhaps there is a 37 // compile-time friendlier way to control/limit the number of specialisations 38 // for recursive functions. 39 // - Don't transform the function if function specialization does not trigger; 40 // the SCCPSolver may make IR changes. 41 // 42 // References: 43 // - 2021 LLVM Dev Mtg “Introducing function specialisation, and can we enable 44 // it by default?”, https://www.youtube.com/watch?v=zJiCjeXgV5Q 45 // 46 //===----------------------------------------------------------------------===// 47 48 #include "llvm/Transforms/IPO/FunctionSpecialization.h" 49 #include "llvm/ADT/Statistic.h" 50 #include "llvm/Analysis/CodeMetrics.h" 51 #include "llvm/Analysis/ConstantFolding.h" 52 #include "llvm/Analysis/InlineCost.h" 53 #include "llvm/Analysis/InstructionSimplify.h" 54 #include "llvm/Analysis/TargetTransformInfo.h" 55 #include "llvm/Analysis/ValueLattice.h" 56 #include "llvm/Analysis/ValueLatticeUtils.h" 57 #include "llvm/Analysis/ValueTracking.h" 58 #include "llvm/IR/IntrinsicInst.h" 59 #include "llvm/Transforms/Scalar/SCCP.h" 60 #include "llvm/Transforms/Utils/Cloning.h" 61 #include "llvm/Transforms/Utils/SCCPSolver.h" 62 #include "llvm/Transforms/Utils/SizeOpts.h" 63 #include <cmath> 64 65 using namespace llvm; 66 67 #define DEBUG_TYPE "function-specialization" 68 69 STATISTIC(NumSpecsCreated, "Number of specializations created"); 70 71 static cl::opt<bool> ForceSpecialization( 72 "force-specialization", cl::init(false), cl::Hidden, cl::desc( 73 "Force function specialization for every call site with a constant " 74 "argument")); 75 76 static cl::opt<unsigned> MaxClones( 77 "funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc( 78 "The maximum number of clones allowed for a single function " 79 "specialization")); 80 81 static cl::opt<unsigned> MaxIncomingPhiValues( 82 "funcspec-max-incoming-phi-values", cl::init(4), cl::Hidden, cl::desc( 83 "The maximum number of incoming values a PHI node can have to be " 84 "considered during the specialization bonus estimation")); 85 86 static cl::opt<unsigned> MinFunctionSize( 87 "funcspec-min-function-size", cl::init(100), cl::Hidden, cl::desc( 88 "Don't specialize functions that have less than this number of " 89 "instructions")); 90 91 static cl::opt<bool> SpecializeOnAddress( 92 "funcspec-on-address", cl::init(false), cl::Hidden, cl::desc( 93 "Enable function specialization on the address of global values")); 94 95 // Disabled by default as it can significantly increase compilation times. 96 // 97 // https://llvm-compile-time-tracker.com 98 // https://github.com/nikic/llvm-compile-time-tracker 99 static cl::opt<bool> SpecializeLiteralConstant( 100 "funcspec-for-literal-constant", cl::init(false), cl::Hidden, cl::desc( 101 "Enable specialization of functions that take a literal constant as an " 102 "argument")); 103 104 // Estimates the instruction cost of all the basic blocks in \p WorkList. 105 // The successors of such blocks are added to the list as long as they are 106 // executable and they have a unique predecessor. \p WorkList represents 107 // the basic blocks of a specialization which become dead once we replace 108 // instructions that are known to be constants. The aim here is to estimate 109 // the combination of size and latency savings in comparison to the non 110 // specialized version of the function. 111 static Cost estimateBasicBlocks(SmallVectorImpl<BasicBlock *> &WorkList, 112 DenseSet<BasicBlock *> &DeadBlocks, 113 ConstMap &KnownConstants, SCCPSolver &Solver, 114 BlockFrequencyInfo &BFI, 115 TargetTransformInfo &TTI) { 116 Cost Bonus = 0; 117 118 // Accumulate the instruction cost of each basic block weighted by frequency. 119 while (!WorkList.empty()) { 120 BasicBlock *BB = WorkList.pop_back_val(); 121 122 uint64_t Weight = BFI.getBlockFreq(BB).getFrequency() / 123 BFI.getEntryFreq(); 124 if (!Weight) 125 continue; 126 127 // These blocks are considered dead as far as the InstCostVisitor is 128 // concerned. They haven't been proven dead yet by the Solver, but 129 // may become if we propagate the constant specialization arguments. 130 if (!DeadBlocks.insert(BB).second) 131 continue; 132 133 for (Instruction &I : *BB) { 134 // Disregard SSA copies. 135 if (auto *II = dyn_cast<IntrinsicInst>(&I)) 136 if (II->getIntrinsicID() == Intrinsic::ssa_copy) 137 continue; 138 // If it's a known constant we have already accounted for it. 139 if (KnownConstants.contains(&I)) 140 continue; 141 142 Bonus += Weight * 143 TTI.getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 144 145 LLVM_DEBUG(dbgs() << "FnSpecialization: Bonus " << Bonus 146 << " after user " << I << "\n"); 147 } 148 149 // Keep adding dead successors to the list as long as they are 150 // executable and they have a unique predecessor. 151 for (BasicBlock *SuccBB : successors(BB)) 152 if (Solver.isBlockExecutable(SuccBB) && 153 SuccBB->getUniquePredecessor() == BB) 154 WorkList.push_back(SuccBB); 155 } 156 return Bonus; 157 } 158 159 static Constant *findConstantFor(Value *V, ConstMap &KnownConstants) { 160 if (auto *C = dyn_cast<Constant>(V)) 161 return C; 162 if (auto It = KnownConstants.find(V); It != KnownConstants.end()) 163 return It->second; 164 return nullptr; 165 } 166 167 Cost InstCostVisitor::getBonusFromPendingPHIs() { 168 Cost Bonus = 0; 169 while (!PendingPHIs.empty()) { 170 Instruction *Phi = PendingPHIs.pop_back_val(); 171 Bonus += getUserBonus(Phi); 172 } 173 return Bonus; 174 } 175 176 Cost InstCostVisitor::getUserBonus(Instruction *User, Value *Use, Constant *C) { 177 // Cache the iterator before visiting. 178 LastVisited = Use ? KnownConstants.insert({Use, C}).first 179 : KnownConstants.end(); 180 181 if (auto *I = dyn_cast<SwitchInst>(User)) 182 return estimateSwitchInst(*I); 183 184 if (auto *I = dyn_cast<BranchInst>(User)) 185 return estimateBranchInst(*I); 186 187 C = visit(*User); 188 if (!C) 189 return 0; 190 191 KnownConstants.insert({User, C}); 192 193 uint64_t Weight = BFI.getBlockFreq(User->getParent()).getFrequency() / 194 BFI.getEntryFreq(); 195 if (!Weight) 196 return 0; 197 198 Cost Bonus = Weight * 199 TTI.getInstructionCost(User, TargetTransformInfo::TCK_SizeAndLatency); 200 201 LLVM_DEBUG(dbgs() << "FnSpecialization: Bonus " << Bonus 202 << " for user " << *User << "\n"); 203 204 for (auto *U : User->users()) 205 if (auto *UI = dyn_cast<Instruction>(U)) 206 if (UI != User && Solver.isBlockExecutable(UI->getParent())) 207 Bonus += getUserBonus(UI, User, C); 208 209 return Bonus; 210 } 211 212 Cost InstCostVisitor::estimateSwitchInst(SwitchInst &I) { 213 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 214 215 if (I.getCondition() != LastVisited->first) 216 return 0; 217 218 auto *C = dyn_cast<ConstantInt>(LastVisited->second); 219 if (!C) 220 return 0; 221 222 BasicBlock *Succ = I.findCaseValue(C)->getCaseSuccessor(); 223 // Initialize the worklist with the dead basic blocks. These are the 224 // destination labels which are different from the one corresponding 225 // to \p C. They should be executable and have a unique predecessor. 226 SmallVector<BasicBlock *> WorkList; 227 for (const auto &Case : I.cases()) { 228 BasicBlock *BB = Case.getCaseSuccessor(); 229 if (BB == Succ || !Solver.isBlockExecutable(BB) || 230 BB->getUniquePredecessor() != I.getParent()) 231 continue; 232 WorkList.push_back(BB); 233 } 234 235 return estimateBasicBlocks(WorkList, DeadBlocks, KnownConstants, Solver, BFI, 236 TTI); 237 } 238 239 Cost InstCostVisitor::estimateBranchInst(BranchInst &I) { 240 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 241 242 if (I.getCondition() != LastVisited->first) 243 return 0; 244 245 BasicBlock *Succ = I.getSuccessor(LastVisited->second->isOneValue()); 246 // Initialize the worklist with the dead successor as long as 247 // it is executable and has a unique predecessor. 248 SmallVector<BasicBlock *> WorkList; 249 if (Solver.isBlockExecutable(Succ) && 250 Succ->getUniquePredecessor() == I.getParent()) 251 WorkList.push_back(Succ); 252 253 return estimateBasicBlocks(WorkList, DeadBlocks, KnownConstants, Solver, BFI, 254 TTI); 255 } 256 257 Constant *InstCostVisitor::visitPHINode(PHINode &I) { 258 if (I.getNumIncomingValues() > MaxIncomingPhiValues) 259 return nullptr; 260 261 bool Inserted = VisitedPHIs.insert(&I).second; 262 Constant *Const = nullptr; 263 264 for (unsigned Idx = 0, E = I.getNumIncomingValues(); Idx != E; ++Idx) { 265 Value *V = I.getIncomingValue(Idx); 266 if (auto *Inst = dyn_cast<Instruction>(V)) 267 if (Inst == &I || DeadBlocks.contains(I.getIncomingBlock(Idx))) 268 continue; 269 Constant *C = findConstantFor(V, KnownConstants); 270 if (!C) { 271 if (Inserted) 272 PendingPHIs.push_back(&I); 273 return nullptr; 274 } 275 if (!Const) 276 Const = C; 277 else if (C != Const) 278 return nullptr; 279 } 280 return Const; 281 } 282 283 Constant *InstCostVisitor::visitFreezeInst(FreezeInst &I) { 284 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 285 286 if (isGuaranteedNotToBeUndefOrPoison(LastVisited->second)) 287 return LastVisited->second; 288 return nullptr; 289 } 290 291 Constant *InstCostVisitor::visitCallBase(CallBase &I) { 292 Function *F = I.getCalledFunction(); 293 if (!F || !canConstantFoldCallTo(&I, F)) 294 return nullptr; 295 296 SmallVector<Constant *, 8> Operands; 297 Operands.reserve(I.getNumOperands()); 298 299 for (unsigned Idx = 0, E = I.getNumOperands() - 1; Idx != E; ++Idx) { 300 Value *V = I.getOperand(Idx); 301 Constant *C = findConstantFor(V, KnownConstants); 302 if (!C) 303 return nullptr; 304 Operands.push_back(C); 305 } 306 307 auto Ops = ArrayRef(Operands.begin(), Operands.end()); 308 return ConstantFoldCall(&I, F, Ops); 309 } 310 311 Constant *InstCostVisitor::visitLoadInst(LoadInst &I) { 312 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 313 314 if (isa<ConstantPointerNull>(LastVisited->second)) 315 return nullptr; 316 return ConstantFoldLoadFromConstPtr(LastVisited->second, I.getType(), DL); 317 } 318 319 Constant *InstCostVisitor::visitGetElementPtrInst(GetElementPtrInst &I) { 320 SmallVector<Constant *, 8> Operands; 321 Operands.reserve(I.getNumOperands()); 322 323 for (unsigned Idx = 0, E = I.getNumOperands(); Idx != E; ++Idx) { 324 Value *V = I.getOperand(Idx); 325 Constant *C = findConstantFor(V, KnownConstants); 326 if (!C) 327 return nullptr; 328 Operands.push_back(C); 329 } 330 331 auto Ops = ArrayRef(Operands.begin(), Operands.end()); 332 return ConstantFoldInstOperands(&I, Ops, DL); 333 } 334 335 Constant *InstCostVisitor::visitSelectInst(SelectInst &I) { 336 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 337 338 if (I.getCondition() != LastVisited->first) 339 return nullptr; 340 341 Value *V = LastVisited->second->isZeroValue() ? I.getFalseValue() 342 : I.getTrueValue(); 343 Constant *C = findConstantFor(V, KnownConstants); 344 return C; 345 } 346 347 Constant *InstCostVisitor::visitCastInst(CastInst &I) { 348 return ConstantFoldCastOperand(I.getOpcode(), LastVisited->second, 349 I.getType(), DL); 350 } 351 352 Constant *InstCostVisitor::visitCmpInst(CmpInst &I) { 353 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 354 355 bool Swap = I.getOperand(1) == LastVisited->first; 356 Value *V = Swap ? I.getOperand(0) : I.getOperand(1); 357 Constant *Other = findConstantFor(V, KnownConstants); 358 if (!Other) 359 return nullptr; 360 361 Constant *Const = LastVisited->second; 362 return Swap ? 363 ConstantFoldCompareInstOperands(I.getPredicate(), Other, Const, DL) 364 : ConstantFoldCompareInstOperands(I.getPredicate(), Const, Other, DL); 365 } 366 367 Constant *InstCostVisitor::visitUnaryOperator(UnaryOperator &I) { 368 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 369 370 return ConstantFoldUnaryOpOperand(I.getOpcode(), LastVisited->second, DL); 371 } 372 373 Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) { 374 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 375 376 bool Swap = I.getOperand(1) == LastVisited->first; 377 Value *V = Swap ? I.getOperand(0) : I.getOperand(1); 378 Constant *Other = findConstantFor(V, KnownConstants); 379 if (!Other) 380 return nullptr; 381 382 Constant *Const = LastVisited->second; 383 return dyn_cast_or_null<Constant>(Swap ? 384 simplifyBinOp(I.getOpcode(), Other, Const, SimplifyQuery(DL)) 385 : simplifyBinOp(I.getOpcode(), Const, Other, SimplifyQuery(DL))); 386 } 387 388 Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca, 389 CallInst *Call) { 390 Value *StoreValue = nullptr; 391 for (auto *User : Alloca->users()) { 392 // We can't use llvm::isAllocaPromotable() as that would fail because of 393 // the usage in the CallInst, which is what we check here. 394 if (User == Call) 395 continue; 396 if (auto *Bitcast = dyn_cast<BitCastInst>(User)) { 397 if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call) 398 return nullptr; 399 continue; 400 } 401 402 if (auto *Store = dyn_cast<StoreInst>(User)) { 403 // This is a duplicate store, bail out. 404 if (StoreValue || Store->isVolatile()) 405 return nullptr; 406 StoreValue = Store->getValueOperand(); 407 continue; 408 } 409 // Bail if there is any other unknown usage. 410 return nullptr; 411 } 412 413 if (!StoreValue) 414 return nullptr; 415 416 return getCandidateConstant(StoreValue); 417 } 418 419 // A constant stack value is an AllocaInst that has a single constant 420 // value stored to it. Return this constant if such an alloca stack value 421 // is a function argument. 422 Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call, 423 Value *Val) { 424 if (!Val) 425 return nullptr; 426 Val = Val->stripPointerCasts(); 427 if (auto *ConstVal = dyn_cast<ConstantInt>(Val)) 428 return ConstVal; 429 auto *Alloca = dyn_cast<AllocaInst>(Val); 430 if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy()) 431 return nullptr; 432 return getPromotableAlloca(Alloca, Call); 433 } 434 435 // To support specializing recursive functions, it is important to propagate 436 // constant arguments because after a first iteration of specialisation, a 437 // reduced example may look like this: 438 // 439 // define internal void @RecursiveFn(i32* arg1) { 440 // %temp = alloca i32, align 4 441 // store i32 2 i32* %temp, align 4 442 // call void @RecursiveFn.1(i32* nonnull %temp) 443 // ret void 444 // } 445 // 446 // Before a next iteration, we need to propagate the constant like so 447 // which allows further specialization in next iterations. 448 // 449 // @funcspec.arg = internal constant i32 2 450 // 451 // define internal void @someFunc(i32* arg1) { 452 // call void @otherFunc(i32* nonnull @funcspec.arg) 453 // ret void 454 // } 455 // 456 // See if there are any new constant values for the callers of \p F via 457 // stack variables and promote them to global variables. 458 void FunctionSpecializer::promoteConstantStackValues(Function *F) { 459 for (User *U : F->users()) { 460 461 auto *Call = dyn_cast<CallInst>(U); 462 if (!Call) 463 continue; 464 465 if (!Solver.isBlockExecutable(Call->getParent())) 466 continue; 467 468 for (const Use &U : Call->args()) { 469 unsigned Idx = Call->getArgOperandNo(&U); 470 Value *ArgOp = Call->getArgOperand(Idx); 471 Type *ArgOpType = ArgOp->getType(); 472 473 if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy()) 474 continue; 475 476 auto *ConstVal = getConstantStackValue(Call, ArgOp); 477 if (!ConstVal) 478 continue; 479 480 Value *GV = new GlobalVariable(M, ConstVal->getType(), true, 481 GlobalValue::InternalLinkage, ConstVal, 482 "funcspec.arg"); 483 if (ArgOpType != ConstVal->getType()) 484 GV = ConstantExpr::getBitCast(cast<Constant>(GV), ArgOpType); 485 486 Call->setArgOperand(Idx, GV); 487 } 488 } 489 } 490 491 // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics 492 // interfere with the promoteConstantStackValues() optimization. 493 static void removeSSACopy(Function &F) { 494 for (BasicBlock &BB : F) { 495 for (Instruction &Inst : llvm::make_early_inc_range(BB)) { 496 auto *II = dyn_cast<IntrinsicInst>(&Inst); 497 if (!II) 498 continue; 499 if (II->getIntrinsicID() != Intrinsic::ssa_copy) 500 continue; 501 Inst.replaceAllUsesWith(II->getOperand(0)); 502 Inst.eraseFromParent(); 503 } 504 } 505 } 506 507 /// Remove any ssa_copy intrinsics that may have been introduced. 508 void FunctionSpecializer::cleanUpSSA() { 509 for (Function *F : Specializations) 510 removeSSACopy(*F); 511 } 512 513 514 template <> struct llvm::DenseMapInfo<SpecSig> { 515 static inline SpecSig getEmptyKey() { return {~0U, {}}; } 516 517 static inline SpecSig getTombstoneKey() { return {~1U, {}}; } 518 519 static unsigned getHashValue(const SpecSig &S) { 520 return static_cast<unsigned>(hash_value(S)); 521 } 522 523 static bool isEqual(const SpecSig &LHS, const SpecSig &RHS) { 524 return LHS == RHS; 525 } 526 }; 527 528 FunctionSpecializer::~FunctionSpecializer() { 529 LLVM_DEBUG( 530 if (NumSpecsCreated > 0) 531 dbgs() << "FnSpecialization: Created " << NumSpecsCreated 532 << " specializations in module " << M.getName() << "\n"); 533 // Eliminate dead code. 534 removeDeadFunctions(); 535 cleanUpSSA(); 536 } 537 538 /// Attempt to specialize functions in the module to enable constant 539 /// propagation across function boundaries. 540 /// 541 /// \returns true if at least one function is specialized. 542 bool FunctionSpecializer::run() { 543 // Find possible specializations for each function. 544 SpecMap SM; 545 SmallVector<Spec, 32> AllSpecs; 546 unsigned NumCandidates = 0; 547 for (Function &F : M) { 548 if (!isCandidateFunction(&F)) 549 continue; 550 551 auto [It, Inserted] = FunctionMetrics.try_emplace(&F); 552 CodeMetrics &Metrics = It->second; 553 //Analyze the function. 554 if (Inserted) { 555 SmallPtrSet<const Value *, 32> EphValues; 556 CodeMetrics::collectEphemeralValues(&F, &GetAC(F), EphValues); 557 for (BasicBlock &BB : F) 558 Metrics.analyzeBasicBlock(&BB, GetTTI(F), EphValues); 559 } 560 561 // If the code metrics reveal that we shouldn't duplicate the function, 562 // or if the code size implies that this function is easy to get inlined, 563 // then we shouldn't specialize it. 564 if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() || 565 (!ForceSpecialization && !F.hasFnAttribute(Attribute::NoInline) && 566 Metrics.NumInsts < MinFunctionSize)) 567 continue; 568 569 // TODO: For now only consider recursive functions when running multiple 570 // times. This should change if specialization on literal constants gets 571 // enabled. 572 if (!Inserted && !Metrics.isRecursive && !SpecializeLiteralConstant) 573 continue; 574 575 LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for " 576 << F.getName() << " is " << Metrics.NumInsts << "\n"); 577 578 if (Inserted && Metrics.isRecursive) 579 promoteConstantStackValues(&F); 580 581 if (!findSpecializations(&F, Metrics.NumInsts, AllSpecs, SM)) { 582 LLVM_DEBUG( 583 dbgs() << "FnSpecialization: No possible specializations found for " 584 << F.getName() << "\n"); 585 continue; 586 } 587 588 ++NumCandidates; 589 } 590 591 if (!NumCandidates) { 592 LLVM_DEBUG( 593 dbgs() 594 << "FnSpecialization: No possible specializations found in module\n"); 595 return false; 596 } 597 598 // Choose the most profitable specialisations, which fit in the module 599 // specialization budget, which is derived from maximum number of 600 // specializations per specialization candidate function. 601 auto CompareScore = [&AllSpecs](unsigned I, unsigned J) { 602 return AllSpecs[I].Score > AllSpecs[J].Score; 603 }; 604 const unsigned NSpecs = 605 std::min(NumCandidates * MaxClones, unsigned(AllSpecs.size())); 606 SmallVector<unsigned> BestSpecs(NSpecs + 1); 607 std::iota(BestSpecs.begin(), BestSpecs.begin() + NSpecs, 0); 608 if (AllSpecs.size() > NSpecs) { 609 LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed " 610 << "the maximum number of clones threshold.\n" 611 << "FnSpecialization: Specializing the " 612 << NSpecs 613 << " most profitable candidates.\n"); 614 std::make_heap(BestSpecs.begin(), BestSpecs.begin() + NSpecs, CompareScore); 615 for (unsigned I = NSpecs, N = AllSpecs.size(); I < N; ++I) { 616 BestSpecs[NSpecs] = I; 617 std::push_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore); 618 std::pop_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore); 619 } 620 } 621 622 LLVM_DEBUG(dbgs() << "FnSpecialization: List of specializations \n"; 623 for (unsigned I = 0; I < NSpecs; ++I) { 624 const Spec &S = AllSpecs[BestSpecs[I]]; 625 dbgs() << "FnSpecialization: Function " << S.F->getName() 626 << " , score " << S.Score << "\n"; 627 for (const ArgInfo &Arg : S.Sig.Args) 628 dbgs() << "FnSpecialization: FormalArg = " 629 << Arg.Formal->getNameOrAsOperand() 630 << ", ActualArg = " << Arg.Actual->getNameOrAsOperand() 631 << "\n"; 632 }); 633 634 // Create the chosen specializations. 635 SmallPtrSet<Function *, 8> OriginalFuncs; 636 SmallVector<Function *> Clones; 637 for (unsigned I = 0; I < NSpecs; ++I) { 638 Spec &S = AllSpecs[BestSpecs[I]]; 639 S.Clone = createSpecialization(S.F, S.Sig); 640 641 // Update the known call sites to call the clone. 642 for (CallBase *Call : S.CallSites) { 643 LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call 644 << " to call " << S.Clone->getName() << "\n"); 645 Call->setCalledFunction(S.Clone); 646 } 647 648 Clones.push_back(S.Clone); 649 OriginalFuncs.insert(S.F); 650 } 651 652 Solver.solveWhileResolvedUndefsIn(Clones); 653 654 // Update the rest of the call sites - these are the recursive calls, calls 655 // to discarded specialisations and calls that may match a specialisation 656 // after the solver runs. 657 for (Function *F : OriginalFuncs) { 658 auto [Begin, End] = SM[F]; 659 updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End); 660 } 661 662 for (Function *F : Clones) { 663 if (F->getReturnType()->isVoidTy()) 664 continue; 665 if (F->getReturnType()->isStructTy()) { 666 auto *STy = cast<StructType>(F->getReturnType()); 667 if (!Solver.isStructLatticeConstant(F, STy)) 668 continue; 669 } else { 670 auto It = Solver.getTrackedRetVals().find(F); 671 assert(It != Solver.getTrackedRetVals().end() && 672 "Return value ought to be tracked"); 673 if (SCCPSolver::isOverdefined(It->second)) 674 continue; 675 } 676 for (User *U : F->users()) { 677 if (auto *CS = dyn_cast<CallBase>(U)) { 678 //The user instruction does not call our function. 679 if (CS->getCalledFunction() != F) 680 continue; 681 Solver.resetLatticeValueFor(CS); 682 } 683 } 684 } 685 686 // Rerun the solver to notify the users of the modified callsites. 687 Solver.solveWhileResolvedUndefs(); 688 689 for (Function *F : OriginalFuncs) 690 if (FunctionMetrics[F].isRecursive) 691 promoteConstantStackValues(F); 692 693 return true; 694 } 695 696 void FunctionSpecializer::removeDeadFunctions() { 697 for (Function *F : FullySpecialized) { 698 LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function " 699 << F->getName() << "\n"); 700 if (FAM) 701 FAM->clear(*F, F->getName()); 702 F->eraseFromParent(); 703 } 704 FullySpecialized.clear(); 705 } 706 707 /// Clone the function \p F and remove the ssa_copy intrinsics added by 708 /// the SCCPSolver in the cloned version. 709 static Function *cloneCandidateFunction(Function *F) { 710 ValueToValueMapTy Mappings; 711 Function *Clone = CloneFunction(F, Mappings); 712 removeSSACopy(*Clone); 713 return Clone; 714 } 715 716 bool FunctionSpecializer::findSpecializations(Function *F, Cost SpecCost, 717 SmallVectorImpl<Spec> &AllSpecs, 718 SpecMap &SM) { 719 // A mapping from a specialisation signature to the index of the respective 720 // entry in the all specialisation array. Used to ensure uniqueness of 721 // specialisations. 722 DenseMap<SpecSig, unsigned> UniqueSpecs; 723 724 // Get a list of interesting arguments. 725 SmallVector<Argument *> Args; 726 for (Argument &Arg : F->args()) 727 if (isArgumentInteresting(&Arg)) 728 Args.push_back(&Arg); 729 730 if (Args.empty()) 731 return false; 732 733 for (User *U : F->users()) { 734 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 735 continue; 736 auto &CS = *cast<CallBase>(U); 737 738 // The user instruction does not call our function. 739 if (CS.getCalledFunction() != F) 740 continue; 741 742 // If the call site has attribute minsize set, that callsite won't be 743 // specialized. 744 if (CS.hasFnAttr(Attribute::MinSize)) 745 continue; 746 747 // If the parent of the call site will never be executed, we don't need 748 // to worry about the passed value. 749 if (!Solver.isBlockExecutable(CS.getParent())) 750 continue; 751 752 // Examine arguments and create a specialisation candidate from the 753 // constant operands of this call site. 754 SpecSig S; 755 for (Argument *A : Args) { 756 Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo())); 757 if (!C) 758 continue; 759 LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument " 760 << A->getName() << " : " << C->getNameOrAsOperand() 761 << "\n"); 762 S.Args.push_back({A, C}); 763 } 764 765 if (S.Args.empty()) 766 continue; 767 768 // Check if we have encountered the same specialisation already. 769 if (auto It = UniqueSpecs.find(S); It != UniqueSpecs.end()) { 770 // Existing specialisation. Add the call to the list to rewrite, unless 771 // it's a recursive call. A specialisation, generated because of a 772 // recursive call may end up as not the best specialisation for all 773 // the cloned instances of this call, which result from specialising 774 // functions. Hence we don't rewrite the call directly, but match it with 775 // the best specialisation once all specialisations are known. 776 if (CS.getFunction() == F) 777 continue; 778 const unsigned Index = It->second; 779 AllSpecs[Index].CallSites.push_back(&CS); 780 } else { 781 // Calculate the specialisation gain. 782 Cost Score = 0; 783 InstCostVisitor Visitor = getInstCostVisitorFor(F); 784 for (ArgInfo &A : S.Args) 785 Score += getSpecializationBonus(A.Formal, A.Actual, Visitor); 786 Score += Visitor.getBonusFromPendingPHIs(); 787 788 LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization score = " 789 << Score << "\n"); 790 791 // Discard unprofitable specialisations. 792 if (!ForceSpecialization && Score <= SpecCost) 793 continue; 794 795 // Create a new specialisation entry. 796 auto &Spec = AllSpecs.emplace_back(F, S, Score); 797 if (CS.getFunction() != F) 798 Spec.CallSites.push_back(&CS); 799 const unsigned Index = AllSpecs.size() - 1; 800 UniqueSpecs[S] = Index; 801 if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted) 802 It->second.second = Index + 1; 803 } 804 } 805 806 return !UniqueSpecs.empty(); 807 } 808 809 bool FunctionSpecializer::isCandidateFunction(Function *F) { 810 if (F->isDeclaration() || F->arg_empty()) 811 return false; 812 813 if (F->hasFnAttribute(Attribute::NoDuplicate)) 814 return false; 815 816 // Do not specialize the cloned function again. 817 if (Specializations.contains(F)) 818 return false; 819 820 // If we're optimizing the function for size, we shouldn't specialize it. 821 if (F->hasOptSize() || 822 shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass)) 823 return false; 824 825 // Exit if the function is not executable. There's no point in specializing 826 // a dead function. 827 if (!Solver.isBlockExecutable(&F->getEntryBlock())) 828 return false; 829 830 // It wastes time to specialize a function which would get inlined finally. 831 if (F->hasFnAttribute(Attribute::AlwaysInline)) 832 return false; 833 834 LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName() 835 << "\n"); 836 return true; 837 } 838 839 Function *FunctionSpecializer::createSpecialization(Function *F, 840 const SpecSig &S) { 841 Function *Clone = cloneCandidateFunction(F); 842 843 // The original function does not neccessarily have internal linkage, but the 844 // clone must. 845 Clone->setLinkage(GlobalValue::InternalLinkage); 846 847 // Initialize the lattice state of the arguments of the function clone, 848 // marking the argument on which we specialized the function constant 849 // with the given value. 850 Solver.setLatticeValueForSpecializationArguments(Clone, S.Args); 851 Solver.markBlockExecutable(&Clone->front()); 852 Solver.addArgumentTrackedFunction(Clone); 853 Solver.addTrackedFunction(Clone); 854 855 // Mark all the specialized functions 856 Specializations.insert(Clone); 857 ++NumSpecsCreated; 858 859 return Clone; 860 } 861 862 /// Compute a bonus for replacing argument \p A with constant \p C. 863 Cost FunctionSpecializer::getSpecializationBonus(Argument *A, Constant *C, 864 InstCostVisitor &Visitor) { 865 LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: " 866 << C->getNameOrAsOperand() << "\n"); 867 868 Cost TotalCost = 0; 869 for (auto *U : A->users()) 870 if (auto *UI = dyn_cast<Instruction>(U)) 871 if (Solver.isBlockExecutable(UI->getParent())) 872 TotalCost += Visitor.getUserBonus(UI, A, C); 873 874 LLVM_DEBUG(dbgs() << "FnSpecialization: Accumulated user bonus " 875 << TotalCost << " for argument " << *A << "\n"); 876 877 // The below heuristic is only concerned with exposing inlining 878 // opportunities via indirect call promotion. If the argument is not a 879 // (potentially casted) function pointer, give up. 880 // 881 // TODO: Perhaps we should consider checking such inlining opportunities 882 // while traversing the users of the specialization arguments ? 883 Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts()); 884 if (!CalledFunction) 885 return TotalCost; 886 887 // Get TTI for the called function (used for the inline cost). 888 auto &CalleeTTI = (GetTTI)(*CalledFunction); 889 890 // Look at all the call sites whose called value is the argument. 891 // Specializing the function on the argument would allow these indirect 892 // calls to be promoted to direct calls. If the indirect call promotion 893 // would likely enable the called function to be inlined, specializing is a 894 // good idea. 895 int Bonus = 0; 896 for (User *U : A->users()) { 897 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 898 continue; 899 auto *CS = cast<CallBase>(U); 900 if (CS->getCalledOperand() != A) 901 continue; 902 if (CS->getFunctionType() != CalledFunction->getFunctionType()) 903 continue; 904 905 // Get the cost of inlining the called function at this call site. Note 906 // that this is only an estimate. The called function may eventually 907 // change in a way that leads to it not being inlined here, even though 908 // inlining looks profitable now. For example, one of its called 909 // functions may be inlined into it, making the called function too large 910 // to be inlined into this call site. 911 // 912 // We apply a boost for performing indirect call promotion by increasing 913 // the default threshold by the threshold for indirect calls. 914 auto Params = getInlineParams(); 915 Params.DefaultThreshold += InlineConstants::IndirectCallThreshold; 916 InlineCost IC = 917 getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI); 918 919 // We clamp the bonus for this call to be between zero and the default 920 // threshold. 921 if (IC.isAlways()) 922 Bonus += Params.DefaultThreshold; 923 else if (IC.isVariable() && IC.getCostDelta() > 0) 924 Bonus += IC.getCostDelta(); 925 926 LLVM_DEBUG(dbgs() << "FnSpecialization: Inlining bonus " << Bonus 927 << " for user " << *U << "\n"); 928 } 929 930 return TotalCost + Bonus; 931 } 932 933 /// Determine if it is possible to specialise the function for constant values 934 /// of the formal parameter \p A. 935 bool FunctionSpecializer::isArgumentInteresting(Argument *A) { 936 // No point in specialization if the argument is unused. 937 if (A->user_empty()) 938 return false; 939 940 Type *Ty = A->getType(); 941 if (!Ty->isPointerTy() && (!SpecializeLiteralConstant || 942 (!Ty->isIntegerTy() && !Ty->isFloatingPointTy() && !Ty->isStructTy()))) 943 return false; 944 945 // SCCP solver does not record an argument that will be constructed on 946 // stack. 947 if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory()) 948 return false; 949 950 // For non-argument-tracked functions every argument is overdefined. 951 if (!Solver.isArgumentTrackedFunction(A->getParent())) 952 return true; 953 954 // Check the lattice value and decide if we should attemt to specialize, 955 // based on this argument. No point in specialization, if the lattice value 956 // is already a constant. 957 bool IsOverdefined = Ty->isStructTy() 958 ? any_of(Solver.getStructLatticeValueFor(A), SCCPSolver::isOverdefined) 959 : SCCPSolver::isOverdefined(Solver.getLatticeValueFor(A)); 960 961 LLVM_DEBUG( 962 if (IsOverdefined) 963 dbgs() << "FnSpecialization: Found interesting parameter " 964 << A->getNameOrAsOperand() << "\n"; 965 else 966 dbgs() << "FnSpecialization: Nothing to do, parameter " 967 << A->getNameOrAsOperand() << " is already constant\n"; 968 ); 969 return IsOverdefined; 970 } 971 972 /// Check if the value \p V (an actual argument) is a constant or can only 973 /// have a constant value. Return that constant. 974 Constant *FunctionSpecializer::getCandidateConstant(Value *V) { 975 if (isa<PoisonValue>(V)) 976 return nullptr; 977 978 // Select for possible specialisation values that are constants or 979 // are deduced to be constants or constant ranges with a single element. 980 Constant *C = dyn_cast<Constant>(V); 981 if (!C) 982 C = Solver.getConstantOrNull(V); 983 984 // Don't specialize on (anything derived from) the address of a non-constant 985 // global variable, unless explicitly enabled. 986 if (C && C->getType()->isPointerTy() && !C->isNullValue()) 987 if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C)); 988 GV && !(GV->isConstant() || SpecializeOnAddress)) 989 return nullptr; 990 991 return C; 992 } 993 994 void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin, 995 const Spec *End) { 996 // Collect the call sites that need updating. 997 SmallVector<CallBase *> ToUpdate; 998 for (User *U : F->users()) 999 if (auto *CS = dyn_cast<CallBase>(U); 1000 CS && CS->getCalledFunction() == F && 1001 Solver.isBlockExecutable(CS->getParent())) 1002 ToUpdate.push_back(CS); 1003 1004 unsigned NCallsLeft = ToUpdate.size(); 1005 for (CallBase *CS : ToUpdate) { 1006 bool ShouldDecrementCount = CS->getFunction() == F; 1007 1008 // Find the best matching specialisation. 1009 const Spec *BestSpec = nullptr; 1010 for (const Spec &S : make_range(Begin, End)) { 1011 if (!S.Clone || (BestSpec && S.Score <= BestSpec->Score)) 1012 continue; 1013 1014 if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) { 1015 unsigned ArgNo = Arg.Formal->getArgNo(); 1016 return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual; 1017 })) 1018 continue; 1019 1020 BestSpec = &S; 1021 } 1022 1023 if (BestSpec) { 1024 LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS 1025 << " to call " << BestSpec->Clone->getName() << "\n"); 1026 CS->setCalledFunction(BestSpec->Clone); 1027 ShouldDecrementCount = true; 1028 } 1029 1030 if (ShouldDecrementCount) 1031 --NCallsLeft; 1032 } 1033 1034 // If the function has been completely specialized, the original function 1035 // is no longer needed. Mark it unreachable. 1036 if (NCallsLeft == 0 && Solver.isArgumentTrackedFunction(F)) { 1037 Solver.markFunctionUnreachable(F); 1038 FullySpecialized.insert(F); 1039 } 1040 } 1041