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