1 //===- MergeFunctions.cpp - Merge identical functions ---------------------===// 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 pass looks for equivalent functions that are mergable and folds them. 10 // 11 // Order relation is defined on set of functions. It was made through 12 // special function comparison procedure that returns 13 // 0 when functions are equal, 14 // -1 when Left function is less than right function, and 15 // 1 for opposite case. We need total-ordering, so we need to maintain 16 // four properties on the functions set: 17 // a <= a (reflexivity) 18 // if a <= b and b <= a then a = b (antisymmetry) 19 // if a <= b and b <= c then a <= c (transitivity). 20 // for all a and b: a <= b or b <= a (totality). 21 // 22 // Comparison iterates through each instruction in each basic block. 23 // Functions are kept on binary tree. For each new function F we perform 24 // lookup in binary tree. 25 // In practice it works the following way: 26 // -- We define Function* container class with custom "operator<" (FunctionPtr). 27 // -- "FunctionPtr" instances are stored in std::set collection, so every 28 // std::set::insert operation will give you result in log(N) time. 29 // 30 // As an optimization, a hash of the function structure is calculated first, and 31 // two functions are only compared if they have the same hash. This hash is 32 // cheap to compute, and has the property that if function F == G according to 33 // the comparison function, then hash(F) == hash(G). This consistency property 34 // is critical to ensuring all possible merging opportunities are exploited. 35 // Collisions in the hash affect the speed of the pass but not the correctness 36 // or determinism of the resulting transformation. 37 // 38 // When a match is found the functions are folded. If both functions are 39 // overridable, we move the functionality into a new internal function and 40 // leave two overridable thunks to it. 41 // 42 //===----------------------------------------------------------------------===// 43 // 44 // Future work: 45 // 46 // * virtual functions. 47 // 48 // Many functions have their address taken by the virtual function table for 49 // the object they belong to. However, as long as it's only used for a lookup 50 // and call, this is irrelevant, and we'd like to fold such functions. 51 // 52 // * be smarter about bitcasts. 53 // 54 // In order to fold functions, we will sometimes add either bitcast instructions 55 // or bitcast constant expressions. Unfortunately, this can confound further 56 // analysis since the two functions differ where one has a bitcast and the 57 // other doesn't. We should learn to look through bitcasts. 58 // 59 // * Compare complex types with pointer types inside. 60 // * Compare cross-reference cases. 61 // * Compare complex expressions. 62 // 63 // All the three issues above could be described as ability to prove that 64 // fA == fB == fC == fE == fF == fG in example below: 65 // 66 // void fA() { 67 // fB(); 68 // } 69 // void fB() { 70 // fA(); 71 // } 72 // 73 // void fE() { 74 // fF(); 75 // } 76 // void fF() { 77 // fG(); 78 // } 79 // void fG() { 80 // fE(); 81 // } 82 // 83 // Simplest cross-reference case (fA <--> fB) was implemented in previous 84 // versions of MergeFunctions, though it presented only in two function pairs 85 // in test-suite (that counts >50k functions) 86 // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A) 87 // could cover much more cases. 88 // 89 //===----------------------------------------------------------------------===// 90 91 #include "llvm/Transforms/IPO/MergeFunctions.h" 92 #include "llvm/ADT/ArrayRef.h" 93 #include "llvm/ADT/SmallVector.h" 94 #include "llvm/ADT/Statistic.h" 95 #include "llvm/IR/Argument.h" 96 #include "llvm/IR/BasicBlock.h" 97 #include "llvm/IR/Constant.h" 98 #include "llvm/IR/Constants.h" 99 #include "llvm/IR/DebugInfoMetadata.h" 100 #include "llvm/IR/DebugLoc.h" 101 #include "llvm/IR/DerivedTypes.h" 102 #include "llvm/IR/Function.h" 103 #include "llvm/IR/GlobalValue.h" 104 #include "llvm/IR/IRBuilder.h" 105 #include "llvm/IR/InstrTypes.h" 106 #include "llvm/IR/Instruction.h" 107 #include "llvm/IR/Instructions.h" 108 #include "llvm/IR/IntrinsicInst.h" 109 #include "llvm/IR/Module.h" 110 #include "llvm/IR/StructuralHash.h" 111 #include "llvm/IR/Type.h" 112 #include "llvm/IR/Use.h" 113 #include "llvm/IR/User.h" 114 #include "llvm/IR/Value.h" 115 #include "llvm/IR/ValueHandle.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Debug.h" 119 #include "llvm/Support/raw_ostream.h" 120 #include "llvm/Transforms/IPO.h" 121 #include "llvm/Transforms/Utils/FunctionComparator.h" 122 #include "llvm/Transforms/Utils/ModuleUtils.h" 123 #include <algorithm> 124 #include <cassert> 125 #include <iterator> 126 #include <set> 127 #include <utility> 128 #include <vector> 129 130 using namespace llvm; 131 132 #define DEBUG_TYPE "mergefunc" 133 134 STATISTIC(NumFunctionsMerged, "Number of functions merged"); 135 STATISTIC(NumThunksWritten, "Number of thunks generated"); 136 STATISTIC(NumAliasesWritten, "Number of aliases generated"); 137 STATISTIC(NumDoubleWeak, "Number of new functions created"); 138 139 static cl::opt<unsigned> NumFunctionsForVerificationCheck( 140 "mergefunc-verify", 141 cl::desc("How many functions in a module could be used for " 142 "MergeFunctions to pass a basic correctness check. " 143 "'0' disables this check. Works only with '-debug' key."), 144 cl::init(0), cl::Hidden); 145 146 // Under option -mergefunc-preserve-debug-info we: 147 // - Do not create a new function for a thunk. 148 // - Retain the debug info for a thunk's parameters (and associated 149 // instructions for the debug info) from the entry block. 150 // Note: -debug will display the algorithm at work. 151 // - Create debug-info for the call (to the shared implementation) made by 152 // a thunk and its return value. 153 // - Erase the rest of the function, retaining the (minimally sized) entry 154 // block to create a thunk. 155 // - Preserve a thunk's call site to point to the thunk even when both occur 156 // within the same translation unit, to aid debugability. Note that this 157 // behaviour differs from the underlying -mergefunc implementation which 158 // modifies the thunk's call site to point to the shared implementation 159 // when both occur within the same translation unit. 160 static cl::opt<bool> 161 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden, 162 cl::init(false), 163 cl::desc("Preserve debug info in thunk when mergefunc " 164 "transformations are made.")); 165 166 static cl::opt<bool> 167 MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden, 168 cl::init(false), 169 cl::desc("Allow mergefunc to create aliases")); 170 171 namespace { 172 173 class FunctionNode { 174 mutable AssertingVH<Function> F; 175 IRHash Hash; 176 177 public: 178 // Note the hash is recalculated potentially multiple times, but it is cheap. 179 FunctionNode(Function *F) : F(F), Hash(StructuralHash(*F)) {} 180 181 Function *getFunc() const { return F; } 182 IRHash getHash() const { return Hash; } 183 184 /// Replace the reference to the function F by the function G, assuming their 185 /// implementations are equal. 186 void replaceBy(Function *G) const { 187 F = G; 188 } 189 }; 190 191 /// MergeFunctions finds functions which will generate identical machine code, 192 /// by considering all pointer types to be equivalent. Once identified, 193 /// MergeFunctions will fold them by replacing a call to one to a call to a 194 /// bitcast of the other. 195 class MergeFunctions { 196 public: 197 MergeFunctions() : FnTree(FunctionNodeCmp(&GlobalNumbers)) { 198 } 199 200 bool runOnModule(Module &M); 201 202 private: 203 // The function comparison operator is provided here so that FunctionNodes do 204 // not need to become larger with another pointer. 205 class FunctionNodeCmp { 206 GlobalNumberState* GlobalNumbers; 207 208 public: 209 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {} 210 211 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const { 212 // Order first by hashes, then full function comparison. 213 if (LHS.getHash() != RHS.getHash()) 214 return LHS.getHash() < RHS.getHash(); 215 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers); 216 return FCmp.compare() < 0; 217 } 218 }; 219 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>; 220 221 GlobalNumberState GlobalNumbers; 222 223 /// A work queue of functions that may have been modified and should be 224 /// analyzed again. 225 std::vector<WeakTrackingVH> Deferred; 226 227 /// Set of values marked as used in llvm.used and llvm.compiler.used. 228 SmallPtrSet<GlobalValue *, 4> Used; 229 230 #ifndef NDEBUG 231 /// Checks the rules of order relation introduced among functions set. 232 /// Returns true, if check has been passed, and false if failed. 233 bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist); 234 #endif 235 236 /// Insert a ComparableFunction into the FnTree, or merge it away if it's 237 /// equal to one that's already present. 238 bool insert(Function *NewFunction); 239 240 /// Remove a Function from the FnTree and queue it up for a second sweep of 241 /// analysis. 242 void remove(Function *F); 243 244 /// Find the functions that use this Value and remove them from FnTree and 245 /// queue the functions. 246 void removeUsers(Value *V); 247 248 /// Replace all direct calls of Old with calls of New. Will bitcast New if 249 /// necessary to make types match. 250 void replaceDirectCallers(Function *Old, Function *New); 251 252 /// Merge two equivalent functions. Upon completion, G may be deleted, or may 253 /// be converted into a thunk. In either case, it should never be visited 254 /// again. 255 void mergeTwoFunctions(Function *F, Function *G); 256 257 /// Fill PDIUnrelatedWL with instructions from the entry block that are 258 /// unrelated to parameter related debug info. 259 void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock, 260 std::vector<Instruction *> &PDIUnrelatedWL); 261 262 /// Erase the rest of the CFG (i.e. barring the entry block). 263 void eraseTail(Function *G); 264 265 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the 266 /// parameter debug info, from the entry block. 267 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL); 268 269 /// Replace G with a simple tail call to bitcast(F). Also (unless 270 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F), 271 /// delete G. 272 void writeThunk(Function *F, Function *G); 273 274 // Replace G with an alias to F (deleting function G) 275 void writeAlias(Function *F, Function *G); 276 277 // Replace G with an alias to F if possible, or a thunk to F if possible. 278 // Returns false if neither is the case. 279 bool writeThunkOrAlias(Function *F, Function *G); 280 281 /// Replace function F with function G in the function tree. 282 void replaceFunctionInTree(const FunctionNode &FN, Function *G); 283 284 /// The set of all distinct functions. Use the insert() and remove() methods 285 /// to modify it. The map allows efficient lookup and deferring of Functions. 286 FnTreeType FnTree; 287 288 // Map functions to the iterators of the FunctionNode which contains them 289 // in the FnTree. This must be updated carefully whenever the FnTree is 290 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid 291 // dangling iterators into FnTree. The invariant that preserves this is that 292 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree. 293 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree; 294 }; 295 } // end anonymous namespace 296 297 PreservedAnalyses MergeFunctionsPass::run(Module &M, 298 ModuleAnalysisManager &AM) { 299 MergeFunctions MF; 300 if (!MF.runOnModule(M)) 301 return PreservedAnalyses::all(); 302 return PreservedAnalyses::none(); 303 } 304 305 #ifndef NDEBUG 306 bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) { 307 if (const unsigned Max = NumFunctionsForVerificationCheck) { 308 unsigned TripleNumber = 0; 309 bool Valid = true; 310 311 dbgs() << "MERGEFUNC-VERIFY: Started for first " << Max << " functions.\n"; 312 313 unsigned i = 0; 314 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(), 315 E = Worklist.end(); 316 I != E && i < Max; ++I, ++i) { 317 unsigned j = i; 318 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max; 319 ++J, ++j) { 320 Function *F1 = cast<Function>(*I); 321 Function *F2 = cast<Function>(*J); 322 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare(); 323 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare(); 324 325 // If F1 <= F2, then F2 >= F1, otherwise report failure. 326 if (Res1 != -Res2) { 327 dbgs() << "MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber 328 << "\n"; 329 dbgs() << *F1 << '\n' << *F2 << '\n'; 330 Valid = false; 331 } 332 333 if (Res1 == 0) 334 continue; 335 336 unsigned k = j; 337 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max; 338 ++k, ++K, ++TripleNumber) { 339 if (K == J) 340 continue; 341 342 Function *F3 = cast<Function>(*K); 343 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare(); 344 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare(); 345 346 bool Transitive = true; 347 348 if (Res1 != 0 && Res1 == Res4) { 349 // F1 > F2, F2 > F3 => F1 > F3 350 Transitive = Res3 == Res1; 351 } else if (Res3 != 0 && Res3 == -Res4) { 352 // F1 > F3, F3 > F2 => F1 > F2 353 Transitive = Res3 == Res1; 354 } else if (Res4 != 0 && -Res3 == Res4) { 355 // F2 > F3, F3 > F1 => F2 > F1 356 Transitive = Res4 == -Res1; 357 } 358 359 if (!Transitive) { 360 dbgs() << "MERGEFUNC-VERIFY: Non-transitive; triple: " 361 << TripleNumber << "\n"; 362 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", " 363 << Res4 << "\n"; 364 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n'; 365 Valid = false; 366 } 367 } 368 } 369 } 370 371 dbgs() << "MERGEFUNC-VERIFY: " << (Valid ? "Passed." : "Failed.") << "\n"; 372 return Valid; 373 } 374 return true; 375 } 376 #endif 377 378 /// Check whether \p F is eligible for function merging. 379 static bool isEligibleForMerging(Function &F) { 380 return !F.isDeclaration() && !F.hasAvailableExternallyLinkage(); 381 } 382 383 bool MergeFunctions::runOnModule(Module &M) { 384 bool Changed = false; 385 386 SmallVector<GlobalValue *, 4> UsedV; 387 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/false); 388 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/true); 389 Used.insert(UsedV.begin(), UsedV.end()); 390 391 // All functions in the module, ordered by hash. Functions with a unique 392 // hash value are easily eliminated. 393 std::vector<std::pair<IRHash, Function *>> HashedFuncs; 394 for (Function &Func : M) { 395 if (isEligibleForMerging(Func)) { 396 HashedFuncs.push_back({StructuralHash(Func), &Func}); 397 } 398 } 399 400 llvm::stable_sort(HashedFuncs, less_first()); 401 402 auto S = HashedFuncs.begin(); 403 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) { 404 // If the hash value matches the previous value or the next one, we must 405 // consider merging it. Otherwise it is dropped and never considered again. 406 if ((I != S && std::prev(I)->first == I->first) || 407 (std::next(I) != IE && std::next(I)->first == I->first) ) { 408 Deferred.push_back(WeakTrackingVH(I->second)); 409 } 410 } 411 412 do { 413 std::vector<WeakTrackingVH> Worklist; 414 Deferred.swap(Worklist); 415 416 LLVM_DEBUG(doFunctionalCheck(Worklist)); 417 418 LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n'); 419 LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n'); 420 421 // Insert functions and merge them. 422 for (WeakTrackingVH &I : Worklist) { 423 if (!I) 424 continue; 425 Function *F = cast<Function>(I); 426 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) { 427 Changed |= insert(F); 428 } 429 } 430 LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n'); 431 } while (!Deferred.empty()); 432 433 FnTree.clear(); 434 FNodesInTree.clear(); 435 GlobalNumbers.clear(); 436 Used.clear(); 437 438 return Changed; 439 } 440 441 // Replace direct callers of Old with New. 442 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) { 443 for (Use &U : llvm::make_early_inc_range(Old->uses())) { 444 CallBase *CB = dyn_cast<CallBase>(U.getUser()); 445 if (CB && CB->isCallee(&U)) { 446 // Do not copy attributes from the called function to the call-site. 447 // Function comparison ensures that the attributes are the same up to 448 // type congruences in byval(), in which case we need to keep the byval 449 // type of the call-site, not the callee function. 450 remove(CB->getFunction()); 451 U.set(New); 452 } 453 } 454 } 455 456 // Helper for writeThunk, 457 // Selects proper bitcast operation, 458 // but a bit simpler then CastInst::getCastOpcode. 459 static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) { 460 Type *SrcTy = V->getType(); 461 if (SrcTy->isStructTy()) { 462 assert(DestTy->isStructTy()); 463 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements()); 464 Value *Result = PoisonValue::get(DestTy); 465 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) { 466 Value *Element = 467 createCast(Builder, Builder.CreateExtractValue(V, ArrayRef(I)), 468 DestTy->getStructElementType(I)); 469 470 Result = Builder.CreateInsertValue(Result, Element, ArrayRef(I)); 471 } 472 return Result; 473 } 474 assert(!DestTy->isStructTy()); 475 if (SrcTy->isIntegerTy() && DestTy->isPointerTy()) 476 return Builder.CreateIntToPtr(V, DestTy); 477 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy()) 478 return Builder.CreatePtrToInt(V, DestTy); 479 else 480 return Builder.CreateBitCast(V, DestTy); 481 } 482 483 // Erase the instructions in PDIUnrelatedWL as they are unrelated to the 484 // parameter debug info, from the entry block. 485 void MergeFunctions::eraseInstsUnrelatedToPDI( 486 std::vector<Instruction *> &PDIUnrelatedWL) { 487 LLVM_DEBUG( 488 dbgs() << " Erasing instructions (in reverse order of appearance in " 489 "entry block) unrelated to parameter debug info from entry " 490 "block: {\n"); 491 while (!PDIUnrelatedWL.empty()) { 492 Instruction *I = PDIUnrelatedWL.back(); 493 LLVM_DEBUG(dbgs() << " Deleting Instruction: "); 494 LLVM_DEBUG(I->print(dbgs())); 495 LLVM_DEBUG(dbgs() << "\n"); 496 I->eraseFromParent(); 497 PDIUnrelatedWL.pop_back(); 498 } 499 LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter " 500 "debug info from entry block. \n"); 501 } 502 503 // Reduce G to its entry block. 504 void MergeFunctions::eraseTail(Function *G) { 505 std::vector<BasicBlock *> WorklistBB; 506 for (BasicBlock &BB : drop_begin(*G)) { 507 BB.dropAllReferences(); 508 WorklistBB.push_back(&BB); 509 } 510 while (!WorklistBB.empty()) { 511 BasicBlock *BB = WorklistBB.back(); 512 BB->eraseFromParent(); 513 WorklistBB.pop_back(); 514 } 515 } 516 517 // We are interested in the following instructions from the entry block as being 518 // related to parameter debug info: 519 // - @llvm.dbg.declare 520 // - stores from the incoming parameters to locations on the stack-frame 521 // - allocas that create these locations on the stack-frame 522 // - @llvm.dbg.value 523 // - the entry block's terminator 524 // The rest are unrelated to debug info for the parameters; fill up 525 // PDIUnrelatedWL with such instructions. 526 void MergeFunctions::filterInstsUnrelatedToPDI( 527 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) { 528 std::set<Instruction *> PDIRelated; 529 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end(); 530 BI != BIE; ++BI) { 531 if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) { 532 LLVM_DEBUG(dbgs() << " Deciding: "); 533 LLVM_DEBUG(BI->print(dbgs())); 534 LLVM_DEBUG(dbgs() << "\n"); 535 DILocalVariable *DILocVar = DVI->getVariable(); 536 if (DILocVar->isParameter()) { 537 LLVM_DEBUG(dbgs() << " Include (parameter): "); 538 LLVM_DEBUG(BI->print(dbgs())); 539 LLVM_DEBUG(dbgs() << "\n"); 540 PDIRelated.insert(&*BI); 541 } else { 542 LLVM_DEBUG(dbgs() << " Delete (!parameter): "); 543 LLVM_DEBUG(BI->print(dbgs())); 544 LLVM_DEBUG(dbgs() << "\n"); 545 } 546 } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) { 547 LLVM_DEBUG(dbgs() << " Deciding: "); 548 LLVM_DEBUG(BI->print(dbgs())); 549 LLVM_DEBUG(dbgs() << "\n"); 550 DILocalVariable *DILocVar = DDI->getVariable(); 551 if (DILocVar->isParameter()) { 552 LLVM_DEBUG(dbgs() << " Parameter: "); 553 LLVM_DEBUG(DILocVar->print(dbgs())); 554 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress()); 555 if (AI) { 556 LLVM_DEBUG(dbgs() << " Processing alloca users: "); 557 LLVM_DEBUG(dbgs() << "\n"); 558 for (User *U : AI->users()) { 559 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 560 if (Value *Arg = SI->getValueOperand()) { 561 if (isa<Argument>(Arg)) { 562 LLVM_DEBUG(dbgs() << " Include: "); 563 LLVM_DEBUG(AI->print(dbgs())); 564 LLVM_DEBUG(dbgs() << "\n"); 565 PDIRelated.insert(AI); 566 LLVM_DEBUG(dbgs() << " Include (parameter): "); 567 LLVM_DEBUG(SI->print(dbgs())); 568 LLVM_DEBUG(dbgs() << "\n"); 569 PDIRelated.insert(SI); 570 LLVM_DEBUG(dbgs() << " Include: "); 571 LLVM_DEBUG(BI->print(dbgs())); 572 LLVM_DEBUG(dbgs() << "\n"); 573 PDIRelated.insert(&*BI); 574 } else { 575 LLVM_DEBUG(dbgs() << " Delete (!parameter): "); 576 LLVM_DEBUG(SI->print(dbgs())); 577 LLVM_DEBUG(dbgs() << "\n"); 578 } 579 } 580 } else { 581 LLVM_DEBUG(dbgs() << " Defer: "); 582 LLVM_DEBUG(U->print(dbgs())); 583 LLVM_DEBUG(dbgs() << "\n"); 584 } 585 } 586 } else { 587 LLVM_DEBUG(dbgs() << " Delete (alloca NULL): "); 588 LLVM_DEBUG(BI->print(dbgs())); 589 LLVM_DEBUG(dbgs() << "\n"); 590 } 591 } else { 592 LLVM_DEBUG(dbgs() << " Delete (!parameter): "); 593 LLVM_DEBUG(BI->print(dbgs())); 594 LLVM_DEBUG(dbgs() << "\n"); 595 } 596 } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) { 597 LLVM_DEBUG(dbgs() << " Will Include Terminator: "); 598 LLVM_DEBUG(BI->print(dbgs())); 599 LLVM_DEBUG(dbgs() << "\n"); 600 PDIRelated.insert(&*BI); 601 } else { 602 LLVM_DEBUG(dbgs() << " Defer: "); 603 LLVM_DEBUG(BI->print(dbgs())); 604 LLVM_DEBUG(dbgs() << "\n"); 605 } 606 } 607 LLVM_DEBUG( 608 dbgs() 609 << " Report parameter debug info related/related instructions: {\n"); 610 for (Instruction &I : *GEntryBlock) { 611 if (PDIRelated.find(&I) == PDIRelated.end()) { 612 LLVM_DEBUG(dbgs() << " !PDIRelated: "); 613 LLVM_DEBUG(I.print(dbgs())); 614 LLVM_DEBUG(dbgs() << "\n"); 615 PDIUnrelatedWL.push_back(&I); 616 } else { 617 LLVM_DEBUG(dbgs() << " PDIRelated: "); 618 LLVM_DEBUG(I.print(dbgs())); 619 LLVM_DEBUG(dbgs() << "\n"); 620 } 621 } 622 LLVM_DEBUG(dbgs() << " }\n"); 623 } 624 625 /// Whether this function may be replaced by a forwarding thunk. 626 static bool canCreateThunkFor(Function *F) { 627 if (F->isVarArg()) 628 return false; 629 630 // Don't merge tiny functions using a thunk, since it can just end up 631 // making the function larger. 632 if (F->size() == 1) { 633 if (F->front().size() <= 2) { 634 LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName() 635 << " is too small to bother creating a thunk for\n"); 636 return false; 637 } 638 } 639 return true; 640 } 641 642 // Replace G with a simple tail call to bitcast(F). Also (unless 643 // MergeFunctionsPDI holds) replace direct uses of G with bitcast(F), 644 // delete G. Under MergeFunctionsPDI, we use G itself for creating 645 // the thunk as we preserve the debug info (and associated instructions) 646 // from G's entry block pertaining to G's incoming arguments which are 647 // passed on as corresponding arguments in the call that G makes to F. 648 // For better debugability, under MergeFunctionsPDI, we do not modify G's 649 // call sites to point to F even when within the same translation unit. 650 void MergeFunctions::writeThunk(Function *F, Function *G) { 651 BasicBlock *GEntryBlock = nullptr; 652 std::vector<Instruction *> PDIUnrelatedWL; 653 BasicBlock *BB = nullptr; 654 Function *NewG = nullptr; 655 if (MergeFunctionsPDI) { 656 LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new " 657 "function as thunk; retain original: " 658 << G->getName() << "()\n"); 659 GEntryBlock = &G->getEntryBlock(); 660 LLVM_DEBUG( 661 dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related " 662 "debug info for " 663 << G->getName() << "() {\n"); 664 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL); 665 GEntryBlock->getTerminator()->eraseFromParent(); 666 BB = GEntryBlock; 667 } else { 668 NewG = Function::Create(G->getFunctionType(), G->getLinkage(), 669 G->getAddressSpace(), "", G->getParent()); 670 NewG->setComdat(G->getComdat()); 671 BB = BasicBlock::Create(F->getContext(), "", NewG); 672 } 673 674 IRBuilder<> Builder(BB); 675 Function *H = MergeFunctionsPDI ? G : NewG; 676 SmallVector<Value *, 16> Args; 677 unsigned i = 0; 678 FunctionType *FFTy = F->getFunctionType(); 679 for (Argument &AI : H->args()) { 680 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i))); 681 ++i; 682 } 683 684 CallInst *CI = Builder.CreateCall(F, Args); 685 ReturnInst *RI = nullptr; 686 bool isSwiftTailCall = F->getCallingConv() == CallingConv::SwiftTail && 687 G->getCallingConv() == CallingConv::SwiftTail; 688 CI->setTailCallKind(isSwiftTailCall ? llvm::CallInst::TCK_MustTail 689 : llvm::CallInst::TCK_Tail); 690 CI->setCallingConv(F->getCallingConv()); 691 CI->setAttributes(F->getAttributes()); 692 if (H->getReturnType()->isVoidTy()) { 693 RI = Builder.CreateRetVoid(); 694 } else { 695 RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType())); 696 } 697 698 if (MergeFunctionsPDI) { 699 DISubprogram *DIS = G->getSubprogram(); 700 if (DIS) { 701 DebugLoc CIDbgLoc = 702 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS); 703 DebugLoc RIDbgLoc = 704 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS); 705 CI->setDebugLoc(CIDbgLoc); 706 RI->setDebugLoc(RIDbgLoc); 707 } else { 708 LLVM_DEBUG( 709 dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for " 710 << G->getName() << "()\n"); 711 } 712 eraseTail(G); 713 eraseInstsUnrelatedToPDI(PDIUnrelatedWL); 714 LLVM_DEBUG( 715 dbgs() << "} // End of parameter related debug info filtering for: " 716 << G->getName() << "()\n"); 717 } else { 718 NewG->copyAttributesFrom(G); 719 NewG->takeName(G); 720 removeUsers(G); 721 G->replaceAllUsesWith(NewG); 722 G->eraseFromParent(); 723 } 724 725 LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n'); 726 ++NumThunksWritten; 727 } 728 729 // Whether this function may be replaced by an alias 730 static bool canCreateAliasFor(Function *F) { 731 if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr()) 732 return false; 733 734 // We should only see linkages supported by aliases here 735 assert(F->hasLocalLinkage() || F->hasExternalLinkage() 736 || F->hasWeakLinkage() || F->hasLinkOnceLinkage()); 737 return true; 738 } 739 740 // Replace G with an alias to F (deleting function G) 741 void MergeFunctions::writeAlias(Function *F, Function *G) { 742 PointerType *PtrType = G->getType(); 743 auto *GA = GlobalAlias::create(G->getValueType(), PtrType->getAddressSpace(), 744 G->getLinkage(), "", F, G->getParent()); 745 746 const MaybeAlign FAlign = F->getAlign(); 747 const MaybeAlign GAlign = G->getAlign(); 748 if (FAlign || GAlign) 749 F->setAlignment(std::max(FAlign.valueOrOne(), GAlign.valueOrOne())); 750 else 751 F->setAlignment(std::nullopt); 752 GA->takeName(G); 753 GA->setVisibility(G->getVisibility()); 754 GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); 755 756 removeUsers(G); 757 G->replaceAllUsesWith(GA); 758 G->eraseFromParent(); 759 760 LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n'); 761 ++NumAliasesWritten; 762 } 763 764 // Replace G with an alias to F if possible, or a thunk to F if 765 // profitable. Returns false if neither is the case. 766 bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) { 767 if (canCreateAliasFor(G)) { 768 writeAlias(F, G); 769 return true; 770 } 771 if (canCreateThunkFor(F)) { 772 writeThunk(F, G); 773 return true; 774 } 775 return false; 776 } 777 778 // Merge two equivalent functions. Upon completion, Function G is deleted. 779 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) { 780 if (F->isInterposable()) { 781 assert(G->isInterposable()); 782 783 // Both writeThunkOrAlias() calls below must succeed, either because we can 784 // create aliases for G and NewF, or because a thunk for F is profitable. 785 // F here has the same signature as NewF below, so that's what we check. 786 if (!canCreateThunkFor(F) && 787 (!canCreateAliasFor(F) || !canCreateAliasFor(G))) 788 return; 789 790 // Make them both thunks to the same internal function. 791 Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(), 792 F->getAddressSpace(), "", F->getParent()); 793 NewF->copyAttributesFrom(F); 794 NewF->takeName(F); 795 removeUsers(F); 796 F->replaceAllUsesWith(NewF); 797 798 // We collect alignment before writeThunkOrAlias that overwrites NewF and 799 // G's content. 800 const MaybeAlign NewFAlign = NewF->getAlign(); 801 const MaybeAlign GAlign = G->getAlign(); 802 803 writeThunkOrAlias(F, G); 804 writeThunkOrAlias(F, NewF); 805 806 if (NewFAlign || GAlign) 807 F->setAlignment(std::max(NewFAlign.valueOrOne(), GAlign.valueOrOne())); 808 else 809 F->setAlignment(std::nullopt); 810 F->setLinkage(GlobalValue::PrivateLinkage); 811 ++NumDoubleWeak; 812 ++NumFunctionsMerged; 813 } else { 814 // For better debugability, under MergeFunctionsPDI, we do not modify G's 815 // call sites to point to F even when within the same translation unit. 816 if (!G->isInterposable() && !MergeFunctionsPDI) { 817 // Functions referred to by llvm.used/llvm.compiler.used are special: 818 // there are uses of the symbol name that are not visible to LLVM, 819 // usually from inline asm. 820 if (G->hasGlobalUnnamedAddr() && !Used.contains(G)) { 821 // G might have been a key in our GlobalNumberState, and it's illegal 822 // to replace a key in ValueMap<GlobalValue *> with a non-global. 823 GlobalNumbers.erase(G); 824 // If G's address is not significant, replace it entirely. 825 removeUsers(G); 826 G->replaceAllUsesWith(F); 827 } else { 828 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI 829 // above). 830 replaceDirectCallers(G, F); 831 } 832 } 833 834 // If G was internal then we may have replaced all uses of G with F. If so, 835 // stop here and delete G. There's no need for a thunk. (See note on 836 // MergeFunctionsPDI above). 837 if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) { 838 G->eraseFromParent(); 839 ++NumFunctionsMerged; 840 return; 841 } 842 843 if (writeThunkOrAlias(F, G)) { 844 ++NumFunctionsMerged; 845 } 846 } 847 } 848 849 /// Replace function F by function G. 850 void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN, 851 Function *G) { 852 Function *F = FN.getFunc(); 853 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 && 854 "The two functions must be equal"); 855 856 auto I = FNodesInTree.find(F); 857 assert(I != FNodesInTree.end() && "F should be in FNodesInTree"); 858 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G"); 859 860 FnTreeType::iterator IterToFNInFnTree = I->second; 861 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree."); 862 // Remove F -> FN and insert G -> FN 863 FNodesInTree.erase(I); 864 FNodesInTree.insert({G, IterToFNInFnTree}); 865 // Replace F with G in FN, which is stored inside the FnTree. 866 FN.replaceBy(G); 867 } 868 869 // Ordering for functions that are equal under FunctionComparator 870 static bool isFuncOrderCorrect(const Function *F, const Function *G) { 871 if (F->isInterposable() != G->isInterposable()) { 872 // Strong before weak, because the weak function may call the strong 873 // one, but not the other way around. 874 return !F->isInterposable(); 875 } 876 if (F->hasLocalLinkage() != G->hasLocalLinkage()) { 877 // External before local, because we definitely have to keep the external 878 // function, but may be able to drop the local one. 879 return !F->hasLocalLinkage(); 880 } 881 // Impose a total order (by name) on the replacement of functions. This is 882 // important when operating on more than one module independently to prevent 883 // cycles of thunks calling each other when the modules are linked together. 884 return F->getName() <= G->getName(); 885 } 886 887 // Insert a ComparableFunction into the FnTree, or merge it away if equal to one 888 // that was already inserted. 889 bool MergeFunctions::insert(Function *NewFunction) { 890 std::pair<FnTreeType::iterator, bool> Result = 891 FnTree.insert(FunctionNode(NewFunction)); 892 893 if (Result.second) { 894 assert(FNodesInTree.count(NewFunction) == 0); 895 FNodesInTree.insert({NewFunction, Result.first}); 896 LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() 897 << '\n'); 898 return false; 899 } 900 901 const FunctionNode &OldF = *Result.first; 902 903 if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) { 904 // Swap the two functions. 905 Function *F = OldF.getFunc(); 906 replaceFunctionInTree(*Result.first, NewFunction); 907 NewFunction = F; 908 assert(OldF.getFunc() != F && "Must have swapped the functions."); 909 } 910 911 LLVM_DEBUG(dbgs() << " " << OldF.getFunc()->getName() 912 << " == " << NewFunction->getName() << '\n'); 913 914 Function *DeleteF = NewFunction; 915 mergeTwoFunctions(OldF.getFunc(), DeleteF); 916 return true; 917 } 918 919 // Remove a function from FnTree. If it was already in FnTree, add 920 // it to Deferred so that we'll look at it in the next round. 921 void MergeFunctions::remove(Function *F) { 922 auto I = FNodesInTree.find(F); 923 if (I != FNodesInTree.end()) { 924 LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n"); 925 FnTree.erase(I->second); 926 // I->second has been invalidated, remove it from the FNodesInTree map to 927 // preserve the invariant. 928 FNodesInTree.erase(I); 929 Deferred.emplace_back(F); 930 } 931 } 932 933 // For each instruction used by the value, remove() the function that contains 934 // the instruction. This should happen right before a call to RAUW. 935 void MergeFunctions::removeUsers(Value *V) { 936 for (User *U : V->users()) 937 if (auto *I = dyn_cast<Instruction>(U)) 938 remove(I->getFunction()); 939 } 940