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