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 (e.g. functions, 10 // globals). Constant parameters like function pointers and constant globals 11 // are propagated to the callee by specializing the function. 12 // 13 // Current limitations: 14 // - It does not yet handle integer ranges. 15 // - Only 1 argument per function is specialised, 16 // - The cost-model could be further looked into, 17 // - We are not yet caching analysis results. 18 // 19 // Ideas: 20 // - With a function specialization attribute for arguments, we could have 21 // a direct way to steer function specialization, avoiding the cost-model, 22 // and thus control compile-times / code-size. 23 // 24 // Todos: 25 // - Limit the times a recursive function get specialized when 26 // `func-specialization-max-iters` 27 // increases linearly. See discussion in https://reviews.llvm.org/D106426 for 28 // details. 29 // - Don't transform the function if there is no function specialization 30 // happens. 31 // 32 //===----------------------------------------------------------------------===// 33 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/Analysis/AssumptionCache.h" 36 #include "llvm/Analysis/CodeMetrics.h" 37 #include "llvm/Analysis/DomTreeUpdater.h" 38 #include "llvm/Analysis/InlineCost.h" 39 #include "llvm/Analysis/LoopInfo.h" 40 #include "llvm/Analysis/TargetLibraryInfo.h" 41 #include "llvm/Analysis/TargetTransformInfo.h" 42 #include "llvm/Transforms/Scalar/SCCP.h" 43 #include "llvm/Transforms/Utils/Cloning.h" 44 #include "llvm/Transforms/Utils/SizeOpts.h" 45 #include <cmath> 46 47 using namespace llvm; 48 49 #define DEBUG_TYPE "function-specialization" 50 51 STATISTIC(NumFuncSpecialized, "Number of functions specialized"); 52 53 static cl::opt<bool> ForceFunctionSpecialization( 54 "force-function-specialization", cl::init(false), cl::Hidden, 55 cl::desc("Force function specialization for every call site with a " 56 "constant argument")); 57 58 static cl::opt<unsigned> FuncSpecializationMaxIters( 59 "func-specialization-max-iters", cl::Hidden, 60 cl::desc("The maximum number of iterations function specialization is run"), 61 cl::init(1)); 62 63 static cl::opt<unsigned> MaxConstantsThreshold( 64 "func-specialization-max-constants", cl::Hidden, 65 cl::desc("The maximum number of clones allowed for a single function " 66 "specialization"), 67 cl::init(3)); 68 69 static cl::opt<unsigned> 70 AvgLoopIterationCount("func-specialization-avg-iters-cost", cl::Hidden, 71 cl::desc("Average loop iteration count cost"), 72 cl::init(10)); 73 74 static cl::opt<bool> EnableSpecializationForLiteralConstant( 75 "function-specialization-for-literal-constant", cl::init(false), cl::Hidden, 76 cl::desc("Make function specialization available for literal constant.")); 77 78 // Helper to check if \p LV is either a constant or a constant 79 // range with a single element. This should cover exactly the same cases as the 80 // old ValueLatticeElement::isConstant() and is intended to be used in the 81 // transition to ValueLatticeElement. 82 static bool isConstant(const ValueLatticeElement &LV) { 83 return LV.isConstant() || 84 (LV.isConstantRange() && LV.getConstantRange().isSingleElement()); 85 } 86 87 // Helper to check if \p LV is either overdefined or a constant int. 88 static bool isOverdefined(const ValueLatticeElement &LV) { 89 return !LV.isUnknownOrUndef() && !isConstant(LV); 90 } 91 92 static Constant *getPromotableAlloca(AllocaInst *Alloca, CallInst *Call) { 93 Value *StoreValue = nullptr; 94 for (auto *User : Alloca->users()) { 95 // We can't use llvm::isAllocaPromotable() as that would fail because of 96 // the usage in the CallInst, which is what we check here. 97 if (User == Call) 98 continue; 99 if (auto *Bitcast = dyn_cast<BitCastInst>(User)) { 100 if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call) 101 return nullptr; 102 continue; 103 } 104 105 if (auto *Store = dyn_cast<StoreInst>(User)) { 106 // This is a duplicate store, bail out. 107 if (StoreValue || Store->isVolatile()) 108 return nullptr; 109 StoreValue = Store->getValueOperand(); 110 continue; 111 } 112 // Bail if there is any other unknown usage. 113 return nullptr; 114 } 115 return dyn_cast_or_null<Constant>(StoreValue); 116 } 117 118 // A constant stack value is an AllocaInst that has a single constant 119 // value stored to it. Return this constant if such an alloca stack value 120 // is a function argument. 121 static Constant *getConstantStackValue(CallInst *Call, Value *Val, 122 SCCPSolver &Solver) { 123 if (!Val) 124 return nullptr; 125 Val = Val->stripPointerCasts(); 126 if (auto *ConstVal = dyn_cast<ConstantInt>(Val)) 127 return ConstVal; 128 auto *Alloca = dyn_cast<AllocaInst>(Val); 129 if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy()) 130 return nullptr; 131 return getPromotableAlloca(Alloca, Call); 132 } 133 134 // To support specializing recursive functions, it is important to propagate 135 // constant arguments because after a first iteration of specialisation, a 136 // reduced example may look like this: 137 // 138 // define internal void @RecursiveFn(i32* arg1) { 139 // %temp = alloca i32, align 4 140 // store i32 2 i32* %temp, align 4 141 // call void @RecursiveFn.1(i32* nonnull %temp) 142 // ret void 143 // } 144 // 145 // Before a next iteration, we need to propagate the constant like so 146 // which allows further specialization in next iterations. 147 // 148 // @funcspec.arg = internal constant i32 2 149 // 150 // define internal void @someFunc(i32* arg1) { 151 // call void @otherFunc(i32* nonnull @funcspec.arg) 152 // ret void 153 // } 154 // 155 static void constantArgPropagation(SmallVectorImpl<Function *> &WorkList, 156 Module &M, SCCPSolver &Solver) { 157 // Iterate over the argument tracked functions see if there 158 // are any new constant values for the call instruction via 159 // stack variables. 160 for (auto *F : WorkList) { 161 // TODO: Generalize for any read only arguments. 162 if (F->arg_size() != 1) 163 continue; 164 165 auto &Arg = *F->arg_begin(); 166 if (!Arg.onlyReadsMemory() || !Arg.getType()->isPointerTy()) 167 continue; 168 169 for (auto *User : F->users()) { 170 auto *Call = dyn_cast<CallInst>(User); 171 if (!Call) 172 break; 173 auto *ArgOp = Call->getArgOperand(0); 174 auto *ArgOpType = ArgOp->getType(); 175 auto *ConstVal = getConstantStackValue(Call, ArgOp, Solver); 176 if (!ConstVal) 177 break; 178 179 Value *GV = new GlobalVariable(M, ConstVal->getType(), true, 180 GlobalValue::InternalLinkage, ConstVal, 181 "funcspec.arg"); 182 183 if (ArgOpType != ConstVal->getType()) 184 GV = ConstantExpr::getBitCast(cast<Constant>(GV), ArgOp->getType()); 185 186 Call->setArgOperand(0, GV); 187 188 // Add the changed CallInst to Solver Worklist 189 Solver.visitCall(*Call); 190 } 191 } 192 } 193 194 // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics 195 // interfere with the constantArgPropagation optimization. 196 static void removeSSACopy(Function &F) { 197 for (BasicBlock &BB : F) { 198 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) { 199 Instruction *Inst = &*BI++; 200 auto *II = dyn_cast<IntrinsicInst>(Inst); 201 if (!II) 202 continue; 203 if (II->getIntrinsicID() != Intrinsic::ssa_copy) 204 continue; 205 Inst->replaceAllUsesWith(II->getOperand(0)); 206 Inst->eraseFromParent(); 207 } 208 } 209 } 210 211 static void removeSSACopy(Module &M) { 212 for (Function &F : M) 213 removeSSACopy(F); 214 } 215 216 class FunctionSpecializer { 217 218 /// The IPSCCP Solver. 219 SCCPSolver &Solver; 220 221 /// Analyses used to help determine if a function should be specialized. 222 std::function<AssumptionCache &(Function &)> GetAC; 223 std::function<TargetTransformInfo &(Function &)> GetTTI; 224 std::function<TargetLibraryInfo &(Function &)> GetTLI; 225 226 SmallPtrSet<Function *, 2> SpecializedFuncs; 227 228 public: 229 FunctionSpecializer(SCCPSolver &Solver, 230 std::function<AssumptionCache &(Function &)> GetAC, 231 std::function<TargetTransformInfo &(Function &)> GetTTI, 232 std::function<TargetLibraryInfo &(Function &)> GetTLI) 233 : Solver(Solver), GetAC(GetAC), GetTTI(GetTTI), GetTLI(GetTLI) {} 234 235 /// Attempt to specialize functions in the module to enable constant 236 /// propagation across function boundaries. 237 /// 238 /// \returns true if at least one function is specialized. 239 bool 240 specializeFunctions(SmallVectorImpl<Function *> &FuncDecls, 241 SmallVectorImpl<Function *> &CurrentSpecializations) { 242 243 // Attempt to specialize the argument-tracked functions. 244 bool Changed = false; 245 for (auto *F : FuncDecls) { 246 if (specializeFunction(F, CurrentSpecializations)) { 247 Changed = true; 248 LLVM_DEBUG(dbgs() << "FnSpecialization: Can specialize this func.\n"); 249 } else { 250 LLVM_DEBUG( 251 dbgs() << "FnSpecialization: Cannot specialize this func.\n"); 252 } 253 } 254 255 for (auto *SpecializedFunc : CurrentSpecializations) { 256 SpecializedFuncs.insert(SpecializedFunc); 257 258 // Initialize the state of the newly created functions, marking them 259 // argument-tracked and executable. 260 if (SpecializedFunc->hasExactDefinition() && 261 !SpecializedFunc->hasFnAttribute(Attribute::Naked)) 262 Solver.addTrackedFunction(SpecializedFunc); 263 Solver.addArgumentTrackedFunction(SpecializedFunc); 264 FuncDecls.push_back(SpecializedFunc); 265 Solver.markBlockExecutable(&SpecializedFunc->front()); 266 267 // Replace the function arguments for the specialized functions. 268 for (Argument &Arg : SpecializedFunc->args()) 269 if (!Arg.use_empty() && tryToReplaceWithConstant(&Arg)) 270 LLVM_DEBUG(dbgs() << "FnSpecialization: Replaced constant argument: " 271 << Arg.getName() << "\n"); 272 } 273 274 NumFuncSpecialized += NbFunctionsSpecialized; 275 return Changed; 276 } 277 278 bool tryToReplaceWithConstant(Value *V) { 279 if (!V->getType()->isSingleValueType() || isa<CallBase>(V) || 280 V->user_empty()) 281 return false; 282 283 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V); 284 if (isOverdefined(IV)) 285 return false; 286 auto *Const = 287 isConstant(IV) ? Solver.getConstant(IV) : UndefValue::get(V->getType()); 288 V->replaceAllUsesWith(Const); 289 290 for (auto *U : Const->users()) 291 if (auto *I = dyn_cast<Instruction>(U)) 292 if (Solver.isBlockExecutable(I->getParent())) 293 Solver.visit(I); 294 295 // Remove the instruction from Block and Solver. 296 if (auto *I = dyn_cast<Instruction>(V)) { 297 if (I->isSafeToRemove()) { 298 I->eraseFromParent(); 299 Solver.removeLatticeValueFor(I); 300 } 301 } 302 return true; 303 } 304 305 private: 306 // The number of functions specialised, used for collecting statistics and 307 // also in the cost model. 308 unsigned NbFunctionsSpecialized = 0; 309 310 /// Clone the function \p F and remove the ssa_copy intrinsics added by 311 /// the SCCPSolver in the cloned version. 312 Function *cloneCandidateFunction(Function *F) { 313 ValueToValueMapTy EmptyMap; 314 Function *Clone = CloneFunction(F, EmptyMap); 315 removeSSACopy(*Clone); 316 return Clone; 317 } 318 319 /// This function decides whether to specialize function \p F based on the 320 /// known constant values its arguments can take on. Specialization is 321 /// performed on the first interesting argument. Specializations based on 322 /// additional arguments will be evaluated on following iterations of the 323 /// main IPSCCP solve loop. \returns true if the function is specialized and 324 /// false otherwise. 325 bool specializeFunction(Function *F, 326 SmallVectorImpl<Function *> &Specializations) { 327 328 // Do not specialize the cloned function again. 329 if (SpecializedFuncs.contains(F)) { 330 return false; 331 } 332 333 // If we're optimizing the function for size, we shouldn't specialize it. 334 if (F->hasOptSize() || 335 shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass)) 336 return false; 337 338 // Exit if the function is not executable. There's no point in specializing 339 // a dead function. 340 if (!Solver.isBlockExecutable(&F->getEntryBlock())) 341 return false; 342 343 LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName() 344 << "\n"); 345 346 // Determine if it would be profitable to create a specialization of the 347 // function where the argument takes on the given constant value. If so, 348 // add the constant to Constants. 349 auto FnSpecCost = getSpecializationCost(F); 350 if (!FnSpecCost.isValid()) { 351 LLVM_DEBUG(dbgs() << "FnSpecialization: Invalid specialisation cost.\n"); 352 return false; 353 } 354 355 LLVM_DEBUG(dbgs() << "FnSpecialization: func specialisation cost: "; 356 FnSpecCost.print(dbgs()); dbgs() << "\n"); 357 358 // Determine if we should specialize the function based on the values the 359 // argument can take on. If specialization is not profitable, we continue 360 // on to the next argument. 361 for (Argument &A : F->args()) { 362 LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing arg: " << A.getName() 363 << "\n"); 364 // True if this will be a partial specialization. We will need to keep 365 // the original function around in addition to the added specializations. 366 bool IsPartial = true; 367 368 // Determine if this argument is interesting. If we know the argument can 369 // take on any constant values, they are collected in Constants. If the 370 // argument can only ever equal a constant value in Constants, the 371 // function will be completely specialized, and the IsPartial flag will 372 // be set to false by isArgumentInteresting (that function only adds 373 // values to the Constants list that are deemed profitable). 374 SmallVector<Constant *, 4> Constants; 375 if (!isArgumentInteresting(&A, Constants, FnSpecCost, IsPartial)) { 376 LLVM_DEBUG(dbgs() << "FnSpecialization: Argument is not interesting\n"); 377 continue; 378 } 379 380 assert(!Constants.empty() && "No constants on which to specialize"); 381 LLVM_DEBUG(dbgs() << "FnSpecialization: Argument is interesting!\n" 382 << "FnSpecialization: Specializing '" << F->getName() 383 << "' on argument: " << A << "\n" 384 << "FnSpecialization: Constants are:\n\n"; 385 for (unsigned I = 0; I < Constants.size(); ++I) dbgs() 386 << *Constants[I] << "\n"; 387 dbgs() << "FnSpecialization: End of constants\n\n"); 388 389 // Create a version of the function in which the argument is marked 390 // constant with the given value. 391 for (auto *C : Constants) { 392 // Clone the function. We leave the ValueToValueMap empty to allow 393 // IPSCCP to propagate the constant arguments. 394 Function *Clone = cloneCandidateFunction(F); 395 Argument *ClonedArg = Clone->arg_begin() + A.getArgNo(); 396 397 // Rewrite calls to the function so that they call the clone instead. 398 rewriteCallSites(F, Clone, *ClonedArg, C); 399 400 // Initialize the lattice state of the arguments of the function clone, 401 // marking the argument on which we specialized the function constant 402 // with the given value. 403 Solver.markArgInFuncSpecialization(F, ClonedArg, C); 404 405 // Mark all the specialized functions 406 Specializations.push_back(Clone); 407 NbFunctionsSpecialized++; 408 } 409 410 // If the function has been completely specialized, the original function 411 // is no longer needed. Mark it unreachable. 412 if (!IsPartial) 413 Solver.markFunctionUnreachable(F); 414 415 // FIXME: Only one argument per function. 416 return true; 417 } 418 419 return false; 420 } 421 422 /// Compute the cost of specializing function \p F. 423 InstructionCost getSpecializationCost(Function *F) { 424 // Compute the code metrics for the function. 425 SmallPtrSet<const Value *, 32> EphValues; 426 CodeMetrics::collectEphemeralValues(F, &(GetAC)(*F), EphValues); 427 CodeMetrics Metrics; 428 for (BasicBlock &BB : *F) 429 Metrics.analyzeBasicBlock(&BB, (GetTTI)(*F), EphValues); 430 431 // If the code metrics reveal that we shouldn't duplicate the function, we 432 // shouldn't specialize it. Set the specialization cost to Invalid. 433 if (Metrics.notDuplicatable) { 434 InstructionCost C{}; 435 C.setInvalid(); 436 return C; 437 } 438 439 // Otherwise, set the specialization cost to be the cost of all the 440 // instructions in the function and penalty for specializing more functions. 441 unsigned Penalty = NbFunctionsSpecialized + 1; 442 return Metrics.NumInsts * InlineConstants::InstrCost * Penalty; 443 } 444 445 InstructionCost getUserBonus(User *U, llvm::TargetTransformInfo &TTI, 446 LoopInfo &LI) { 447 auto *I = dyn_cast_or_null<Instruction>(U); 448 // If not an instruction we do not know how to evaluate. 449 // Keep minimum possible cost for now so that it doesnt affect 450 // specialization. 451 if (!I) 452 return std::numeric_limits<unsigned>::min(); 453 454 auto Cost = TTI.getUserCost(U, TargetTransformInfo::TCK_SizeAndLatency); 455 456 // Traverse recursively if there are more uses. 457 // TODO: Any other instructions to be added here? 458 if (I->mayReadFromMemory() || I->isCast()) 459 for (auto *User : I->users()) 460 Cost += getUserBonus(User, TTI, LI); 461 462 // Increase the cost if it is inside the loop. 463 auto LoopDepth = LI.getLoopDepth(I->getParent()); 464 Cost *= std::pow((double)AvgLoopIterationCount, LoopDepth); 465 return Cost; 466 } 467 468 /// Compute a bonus for replacing argument \p A with constant \p C. 469 InstructionCost getSpecializationBonus(Argument *A, Constant *C) { 470 Function *F = A->getParent(); 471 DominatorTree DT(*F); 472 LoopInfo LI(DT); 473 auto &TTI = (GetTTI)(*F); 474 LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for: " << *A 475 << "\n"); 476 477 InstructionCost TotalCost = 0; 478 for (auto *U : A->users()) { 479 TotalCost += getUserBonus(U, TTI, LI); 480 LLVM_DEBUG(dbgs() << "FnSpecialization: User cost "; 481 TotalCost.print(dbgs()); dbgs() << " for: " << *U << "\n"); 482 } 483 484 // The below heuristic is only concerned with exposing inlining 485 // opportunities via indirect call promotion. If the argument is not a 486 // function pointer, give up. 487 if (!isa<PointerType>(A->getType()) || 488 !isa<FunctionType>(A->getType()->getPointerElementType())) 489 return TotalCost; 490 491 // Since the argument is a function pointer, its incoming constant values 492 // should be functions or constant expressions. The code below attempts to 493 // look through cast expressions to find the function that will be called. 494 Value *CalledValue = C; 495 while (isa<ConstantExpr>(CalledValue) && 496 cast<ConstantExpr>(CalledValue)->isCast()) 497 CalledValue = cast<User>(CalledValue)->getOperand(0); 498 Function *CalledFunction = dyn_cast<Function>(CalledValue); 499 if (!CalledFunction) 500 return TotalCost; 501 502 // Get TTI for the called function (used for the inline cost). 503 auto &CalleeTTI = (GetTTI)(*CalledFunction); 504 505 // Look at all the call sites whose called value is the argument. 506 // Specializing the function on the argument would allow these indirect 507 // calls to be promoted to direct calls. If the indirect call promotion 508 // would likely enable the called function to be inlined, specializing is a 509 // good idea. 510 int Bonus = 0; 511 for (User *U : A->users()) { 512 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 513 continue; 514 auto *CS = cast<CallBase>(U); 515 if (CS->getCalledOperand() != A) 516 continue; 517 518 // Get the cost of inlining the called function at this call site. Note 519 // that this is only an estimate. The called function may eventually 520 // change in a way that leads to it not being inlined here, even though 521 // inlining looks profitable now. For example, one of its called 522 // functions may be inlined into it, making the called function too large 523 // to be inlined into this call site. 524 // 525 // We apply a boost for performing indirect call promotion by increasing 526 // the default threshold by the threshold for indirect calls. 527 auto Params = getInlineParams(); 528 Params.DefaultThreshold += InlineConstants::IndirectCallThreshold; 529 InlineCost IC = 530 getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI); 531 532 // We clamp the bonus for this call to be between zero and the default 533 // threshold. 534 if (IC.isAlways()) 535 Bonus += Params.DefaultThreshold; 536 else if (IC.isVariable() && IC.getCostDelta() > 0) 537 Bonus += IC.getCostDelta(); 538 } 539 540 return TotalCost + Bonus; 541 } 542 543 /// Determine if we should specialize a function based on the incoming values 544 /// of the given argument. 545 /// 546 /// This function implements the goal-directed heuristic. It determines if 547 /// specializing the function based on the incoming values of argument \p A 548 /// would result in any significant optimization opportunities. If 549 /// optimization opportunities exist, the constant values of \p A on which to 550 /// specialize the function are collected in \p Constants. If the values in 551 /// \p Constants represent the complete set of values that \p A can take on, 552 /// the function will be completely specialized, and the \p IsPartial flag is 553 /// set to false. 554 /// 555 /// \returns true if the function should be specialized on the given 556 /// argument. 557 bool isArgumentInteresting(Argument *A, 558 SmallVectorImpl<Constant *> &Constants, 559 const InstructionCost &FnSpecCost, 560 bool &IsPartial) { 561 // For now, don't attempt to specialize functions based on the values of 562 // composite types. 563 if (!A->getType()->isSingleValueType() || A->user_empty()) 564 return false; 565 566 // If the argument isn't overdefined, there's nothing to do. It should 567 // already be constant. 568 if (!Solver.getLatticeValueFor(A).isOverdefined()) { 569 LLVM_DEBUG(dbgs() << "FnSpecialization: nothing to do, arg is already " 570 << "constant?\n"); 571 return false; 572 } 573 574 // Collect the constant values that the argument can take on. If the 575 // argument can't take on any constant values, we aren't going to 576 // specialize the function. While it's possible to specialize the function 577 // based on non-constant arguments, there's likely not much benefit to 578 // constant propagation in doing so. 579 // 580 // TODO 1: currently it won't specialize if there are over the threshold of 581 // calls using the same argument, e.g foo(a) x 4 and foo(b) x 1, but it 582 // might be beneficial to take the occurrences into account in the cost 583 // model, so we would need to find the unique constants. 584 // 585 // TODO 2: this currently does not support constants, i.e. integer ranges. 586 // 587 SmallVector<Constant *, 4> PossibleConstants; 588 bool AllConstant = getPossibleConstants(A, PossibleConstants); 589 if (PossibleConstants.empty()) { 590 LLVM_DEBUG(dbgs() << "FnSpecialization: no possible constants found\n"); 591 return false; 592 } 593 if (PossibleConstants.size() > MaxConstantsThreshold) { 594 LLVM_DEBUG(dbgs() << "FnSpecialization: number of constants found exceed " 595 << "the maximum number of constants threshold.\n"); 596 return false; 597 } 598 599 for (auto *C : PossibleConstants) { 600 LLVM_DEBUG(dbgs() << "FnSpecialization: Constant: " << *C << "\n"); 601 if (ForceFunctionSpecialization) { 602 LLVM_DEBUG(dbgs() << "FnSpecialization: Forced!\n"); 603 Constants.push_back(C); 604 continue; 605 } 606 if (getSpecializationBonus(A, C) > FnSpecCost) { 607 LLVM_DEBUG(dbgs() << "FnSpecialization: profitable!\n"); 608 Constants.push_back(C); 609 } else { 610 LLVM_DEBUG(dbgs() << "FnSpecialization: not profitable\n"); 611 } 612 } 613 614 // None of the constant values the argument can take on were deemed good 615 // candidates on which to specialize the function. 616 if (Constants.empty()) 617 return false; 618 619 // This will be a partial specialization if some of the constants were 620 // rejected due to their profitability. 621 IsPartial = !AllConstant || PossibleConstants.size() != Constants.size(); 622 623 return true; 624 } 625 626 /// Collect in \p Constants all the constant values that argument \p A can 627 /// take on. 628 /// 629 /// \returns true if all of the values the argument can take on are constant 630 /// (e.g., the argument's parent function cannot be called with an 631 /// overdefined value). 632 bool getPossibleConstants(Argument *A, 633 SmallVectorImpl<Constant *> &Constants) { 634 Function *F = A->getParent(); 635 bool AllConstant = true; 636 637 // Iterate over all the call sites of the argument's parent function. 638 for (User *U : F->users()) { 639 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 640 continue; 641 auto &CS = *cast<CallBase>(U); 642 643 // If the parent of the call site will never be executed, we don't need 644 // to worry about the passed value. 645 if (!Solver.isBlockExecutable(CS.getParent())) 646 continue; 647 648 auto *V = CS.getArgOperand(A->getArgNo()); 649 // TrackValueOfGlobalVariable only tracks scalar global variables. 650 if (auto *GV = dyn_cast<GlobalVariable>(V)) { 651 if (!GV->getValueType()->isSingleValueType()) { 652 return false; 653 } 654 } 655 656 if (isa<Constant>(V) && (Solver.getLatticeValueFor(V).isConstant() || 657 EnableSpecializationForLiteralConstant)) 658 Constants.push_back(cast<Constant>(V)); 659 else 660 AllConstant = false; 661 } 662 663 // If the argument can only take on constant values, AllConstant will be 664 // true. 665 return AllConstant; 666 } 667 668 /// Rewrite calls to function \p F to call function \p Clone instead. 669 /// 670 /// This function modifies calls to function \p F whose argument at index \p 671 /// ArgNo is equal to constant \p C. The calls are rewritten to call function 672 /// \p Clone instead. 673 void rewriteCallSites(Function *F, Function *Clone, Argument &Arg, 674 Constant *C) { 675 unsigned ArgNo = Arg.getArgNo(); 676 SmallVector<CallBase *, 4> CallSitesToRewrite; 677 for (auto *U : F->users()) { 678 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 679 continue; 680 auto &CS = *cast<CallBase>(U); 681 if (!CS.getCalledFunction() || CS.getCalledFunction() != F) 682 continue; 683 CallSitesToRewrite.push_back(&CS); 684 } 685 for (auto *CS : CallSitesToRewrite) { 686 if ((CS->getFunction() == Clone && CS->getArgOperand(ArgNo) == &Arg) || 687 CS->getArgOperand(ArgNo) == C) { 688 CS->setCalledFunction(Clone); 689 Solver.markOverdefined(CS); 690 } 691 } 692 } 693 }; 694 695 bool llvm::runFunctionSpecialization( 696 Module &M, const DataLayout &DL, 697 std::function<TargetLibraryInfo &(Function &)> GetTLI, 698 std::function<TargetTransformInfo &(Function &)> GetTTI, 699 std::function<AssumptionCache &(Function &)> GetAC, 700 function_ref<AnalysisResultsForFn(Function &)> GetAnalysis) { 701 SCCPSolver Solver(DL, GetTLI, M.getContext()); 702 FunctionSpecializer FS(Solver, GetAC, GetTTI, GetTLI); 703 bool Changed = false; 704 705 // Loop over all functions, marking arguments to those with their addresses 706 // taken or that are external as overdefined. 707 for (Function &F : M) { 708 if (F.isDeclaration()) 709 continue; 710 if (F.hasFnAttribute(Attribute::NoDuplicate)) 711 continue; 712 713 LLVM_DEBUG(dbgs() << "\nFnSpecialization: Analysing decl: " << F.getName() 714 << "\n"); 715 Solver.addAnalysis(F, GetAnalysis(F)); 716 717 // Determine if we can track the function's arguments. If so, add the 718 // function to the solver's set of argument-tracked functions. 719 if (canTrackArgumentsInterprocedurally(&F)) { 720 LLVM_DEBUG(dbgs() << "FnSpecialization: Can track arguments\n"); 721 Solver.addArgumentTrackedFunction(&F); 722 continue; 723 } else { 724 LLVM_DEBUG(dbgs() << "FnSpecialization: Can't track arguments!\n" 725 << "FnSpecialization: Doesn't have local linkage, or " 726 << "has its address taken\n"); 727 } 728 729 // Assume the function is called. 730 Solver.markBlockExecutable(&F.front()); 731 732 // Assume nothing about the incoming arguments. 733 for (Argument &AI : F.args()) 734 Solver.markOverdefined(&AI); 735 } 736 737 // Determine if we can track any of the module's global variables. If so, add 738 // the global variables we can track to the solver's set of tracked global 739 // variables. 740 for (GlobalVariable &G : M.globals()) { 741 G.removeDeadConstantUsers(); 742 if (canTrackGlobalVariableInterprocedurally(&G)) 743 Solver.trackValueOfGlobalVariable(&G); 744 } 745 746 // Solve for constants. 747 auto RunSCCPSolver = [&](auto &WorkList) { 748 bool ResolvedUndefs = true; 749 750 while (ResolvedUndefs) { 751 LLVM_DEBUG(dbgs() << "FnSpecialization: Running solver\n"); 752 Solver.solve(); 753 LLVM_DEBUG(dbgs() << "FnSpecialization: Resolving undefs\n"); 754 ResolvedUndefs = false; 755 for (Function *F : WorkList) 756 if (Solver.resolvedUndefsIn(*F)) 757 ResolvedUndefs = true; 758 } 759 760 for (auto *F : WorkList) { 761 for (BasicBlock &BB : *F) { 762 if (!Solver.isBlockExecutable(&BB)) 763 continue; 764 for (auto &I : make_early_inc_range(BB)) 765 // FIXME: The solver may make changes to the function here, so set Changed, even if later 766 // function specialization does not trigger. 767 Changed |= FS.tryToReplaceWithConstant(&I); 768 } 769 } 770 }; 771 772 auto &TrackedFuncs = Solver.getArgumentTrackedFunctions(); 773 SmallVector<Function *, 16> FuncDecls(TrackedFuncs.begin(), 774 TrackedFuncs.end()); 775 #ifndef NDEBUG 776 LLVM_DEBUG(dbgs() << "FnSpecialization: Worklist fn decls:\n"); 777 for (auto *F : FuncDecls) 778 LLVM_DEBUG(dbgs() << "FnSpecialization: *) " << F->getName() << "\n"); 779 #endif 780 781 // Initially resolve the constants in all the argument tracked functions. 782 RunSCCPSolver(FuncDecls); 783 784 SmallVector<Function *, 2> CurrentSpecializations; 785 unsigned I = 0; 786 while (FuncSpecializationMaxIters != I++ && 787 FS.specializeFunctions(FuncDecls, CurrentSpecializations)) { 788 789 // Run the solver for the specialized functions. 790 RunSCCPSolver(CurrentSpecializations); 791 792 // Replace some unresolved constant arguments 793 constantArgPropagation(FuncDecls, M, Solver); 794 795 CurrentSpecializations.clear(); 796 Changed = true; 797 } 798 799 // Clean up the IR by removing ssa_copy intrinsics. 800 removeSSACopy(M); 801 return Changed; 802 } 803