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