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 // A hash is computed from the function, based on its type and number of 13 // basic blocks. 14 // 15 // Once all hashes are computed, we perform an expensive equality comparison 16 // on each function pair. This takes n^2/2 comparisons per bucket, so it's 17 // important that the hash function be high quality. The equality comparison 18 // iterates through each instruction in each basic block. 19 // 20 // When a match is found, the functions are folded. We can only fold two 21 // functions when we know that the definition of one of them is not 22 // overridable. 23 // 24 //===----------------------------------------------------------------------===// 25 // 26 // Future work: 27 // 28 // * fold vector<T*>::push_back and vector<S*>::push_back. 29 // 30 // These two functions have different types, but in a way that doesn't matter 31 // to us. As long as we never see an S or T itself, using S* and S** is the 32 // same as using a T* and T**. 33 // 34 // * virtual functions. 35 // 36 // Many functions have their address taken by the virtual function table for 37 // the object they belong to. However, as long as it's only used for a lookup 38 // and call, this is irrelevant, and we'd like to fold such implementations. 39 // 40 //===----------------------------------------------------------------------===// 41 42 #define DEBUG_TYPE "mergefunc" 43 #include "llvm/Transforms/IPO.h" 44 #include "llvm/ADT/DenseMap.h" 45 #include "llvm/ADT/FoldingSet.h" 46 #include "llvm/ADT/Statistic.h" 47 #include "llvm/Constants.h" 48 #include "llvm/InlineAsm.h" 49 #include "llvm/Instructions.h" 50 #include "llvm/LLVMContext.h" 51 #include "llvm/Module.h" 52 #include "llvm/Pass.h" 53 #include "llvm/Support/CallSite.h" 54 #include "llvm/Support/Compiler.h" 55 #include "llvm/Support/Debug.h" 56 #include <map> 57 #include <vector> 58 using namespace llvm; 59 60 STATISTIC(NumFunctionsMerged, "Number of functions merged"); 61 62 namespace { 63 struct VISIBILITY_HIDDEN MergeFunctions : public ModulePass { 64 static char ID; // Pass identification, replacement for typeid 65 MergeFunctions() : ModulePass((intptr_t)&ID) {} 66 67 bool runOnModule(Module &M); 68 }; 69 } 70 71 char MergeFunctions::ID = 0; 72 static RegisterPass<MergeFunctions> 73 X("mergefunc", "Merge Functions"); 74 75 ModulePass *llvm::createMergeFunctionsPass() { 76 return new MergeFunctions(); 77 } 78 79 // ===----------------------------------------------------------------------=== 80 // Comparison of functions 81 // ===----------------------------------------------------------------------=== 82 83 static unsigned long hash(const Function *F) { 84 const FunctionType *FTy = F->getFunctionType(); 85 86 FoldingSetNodeID ID; 87 ID.AddInteger(F->size()); 88 ID.AddInteger(F->getCallingConv()); 89 ID.AddBoolean(F->hasGC()); 90 ID.AddBoolean(FTy->isVarArg()); 91 ID.AddInteger(FTy->getReturnType()->getTypeID()); 92 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 93 ID.AddInteger(FTy->getParamType(i)->getTypeID()); 94 return ID.ComputeHash(); 95 } 96 97 /// IgnoreBitcasts - given a bitcast, returns the first non-bitcast found by 98 /// walking the chain of cast operands. Otherwise, returns the argument. 99 static Value* IgnoreBitcasts(Value *V) { 100 while (BitCastInst *BC = dyn_cast<BitCastInst>(V)) 101 V = BC->getOperand(0); 102 103 return V; 104 } 105 106 /// isEquivalentType - any two pointers are equivalent. Otherwise, standard 107 /// type equivalence rules apply. 108 static bool isEquivalentType(const Type *Ty1, const Type *Ty2) { 109 if (Ty1 == Ty2) 110 return true; 111 if (Ty1->getTypeID() != Ty2->getTypeID()) 112 return false; 113 114 switch(Ty1->getTypeID()) { 115 case Type::VoidTyID: 116 case Type::FloatTyID: 117 case Type::DoubleTyID: 118 case Type::X86_FP80TyID: 119 case Type::FP128TyID: 120 case Type::PPC_FP128TyID: 121 case Type::LabelTyID: 122 case Type::MetadataTyID: 123 return true; 124 125 case Type::IntegerTyID: 126 case Type::OpaqueTyID: 127 // Ty1 == Ty2 would have returned true earlier. 128 return false; 129 130 default: 131 assert(0 && "Unknown type!"); 132 return false; 133 134 case Type::PointerTyID: { 135 const PointerType *PTy1 = cast<PointerType>(Ty1); 136 const PointerType *PTy2 = cast<PointerType>(Ty2); 137 return PTy1->getAddressSpace() == PTy2->getAddressSpace(); 138 } 139 140 case Type::StructTyID: { 141 const StructType *STy1 = cast<StructType>(Ty1); 142 const StructType *STy2 = cast<StructType>(Ty2); 143 if (STy1->getNumElements() != STy2->getNumElements()) 144 return false; 145 146 if (STy1->isPacked() != STy2->isPacked()) 147 return false; 148 149 for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) { 150 if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i))) 151 return false; 152 } 153 return true; 154 } 155 156 case Type::FunctionTyID: { 157 const FunctionType *FTy1 = cast<FunctionType>(Ty1); 158 const FunctionType *FTy2 = cast<FunctionType>(Ty2); 159 if (FTy1->getNumParams() != FTy2->getNumParams() || 160 FTy1->isVarArg() != FTy2->isVarArg()) 161 return false; 162 163 if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType())) 164 return false; 165 166 for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) { 167 if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i))) 168 return false; 169 } 170 return true; 171 } 172 173 case Type::ArrayTyID: 174 case Type::VectorTyID: { 175 const SequentialType *STy1 = cast<SequentialType>(Ty1); 176 const SequentialType *STy2 = cast<SequentialType>(Ty2); 177 return isEquivalentType(STy1->getElementType(), STy2->getElementType()); 178 } 179 } 180 } 181 182 /// isEquivalentOperation - determine whether the two operations are the same 183 /// except that pointer-to-A and pointer-to-B are equivalent. This should be 184 /// kept in sync with Instruction::isSameOperationAs. 185 static bool 186 isEquivalentOperation(const Instruction *I1, const Instruction *I2) { 187 if (I1->getOpcode() != I2->getOpcode() || 188 I1->getNumOperands() != I2->getNumOperands() || 189 !isEquivalentType(I1->getType(), I2->getType())) 190 return false; 191 192 // We have two instructions of identical opcode and #operands. Check to see 193 // if all operands are the same type 194 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i) 195 if (!isEquivalentType(I1->getOperand(i)->getType(), 196 I2->getOperand(i)->getType())) 197 return false; 198 199 // Check special state that is a part of some instructions. 200 if (const LoadInst *LI = dyn_cast<LoadInst>(I1)) 201 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() && 202 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment(); 203 if (const StoreInst *SI = dyn_cast<StoreInst>(I1)) 204 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() && 205 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment(); 206 if (const CmpInst *CI = dyn_cast<CmpInst>(I1)) 207 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate(); 208 if (const CallInst *CI = dyn_cast<CallInst>(I1)) 209 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() && 210 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() && 211 CI->getAttributes().getRawPointer() == 212 cast<CallInst>(I2)->getAttributes().getRawPointer(); 213 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1)) 214 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() && 215 CI->getAttributes().getRawPointer() == 216 cast<InvokeInst>(I2)->getAttributes().getRawPointer(); 217 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) { 218 if (IVI->getNumIndices() != cast<InsertValueInst>(I2)->getNumIndices()) 219 return false; 220 for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i) 221 if (IVI->idx_begin()[i] != cast<InsertValueInst>(I2)->idx_begin()[i]) 222 return false; 223 return true; 224 } 225 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) { 226 if (EVI->getNumIndices() != cast<ExtractValueInst>(I2)->getNumIndices()) 227 return false; 228 for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i) 229 if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I2)->idx_begin()[i]) 230 return false; 231 return true; 232 } 233 234 return true; 235 } 236 237 static bool compare(const Value *V, const Value *U) { 238 assert(!isa<BasicBlock>(V) && !isa<BasicBlock>(U) && 239 "Must not compare basic blocks."); 240 241 assert(isEquivalentType(V->getType(), U->getType()) && 242 "Two of the same operation have operands of different type."); 243 244 // TODO: If the constant is an expression of F, we should accept that it's 245 // equal to the same expression in terms of G. 246 if (isa<Constant>(V)) 247 return V == U; 248 249 // The caller has ensured that ValueMap[V] != U. Since Arguments are 250 // pre-loaded into the ValueMap, and Instructions are added as we go, we know 251 // that this can only be a mis-match. 252 if (isa<Instruction>(V) || isa<Argument>(V)) 253 return false; 254 255 if (isa<InlineAsm>(V) && isa<InlineAsm>(U)) { 256 const InlineAsm *IAF = cast<InlineAsm>(V); 257 const InlineAsm *IAG = cast<InlineAsm>(U); 258 return IAF->getAsmString() == IAG->getAsmString() && 259 IAF->getConstraintString() == IAG->getConstraintString(); 260 } 261 262 return false; 263 } 264 265 static bool equals(const BasicBlock *BB1, const BasicBlock *BB2, 266 DenseMap<const Value *, const Value *> &ValueMap, 267 DenseMap<const Value *, const Value *> &SpeculationMap) { 268 // Speculatively add it anyways. If it's false, we'll notice a difference 269 // later, and this won't matter. 270 ValueMap[BB1] = BB2; 271 272 BasicBlock::const_iterator FI = BB1->begin(), FE = BB1->end(); 273 BasicBlock::const_iterator GI = BB2->begin(), GE = BB2->end(); 274 275 do { 276 if (isa<BitCastInst>(FI)) { 277 ++FI; 278 continue; 279 } 280 if (isa<BitCastInst>(GI)) { 281 ++GI; 282 continue; 283 } 284 285 if (!isEquivalentOperation(FI, GI)) 286 return false; 287 288 if (isa<GetElementPtrInst>(FI)) { 289 const GetElementPtrInst *GEPF = cast<GetElementPtrInst>(FI); 290 const GetElementPtrInst *GEPG = cast<GetElementPtrInst>(GI); 291 if (GEPF->hasAllZeroIndices() && GEPG->hasAllZeroIndices()) { 292 // It's effectively a bitcast. 293 ++FI, ++GI; 294 continue; 295 } 296 297 // TODO: we only really care about the elements before the index 298 if (FI->getOperand(0)->getType() != GI->getOperand(0)->getType()) 299 return false; 300 } 301 302 if (ValueMap[FI] == GI) { 303 ++FI, ++GI; 304 continue; 305 } 306 307 if (ValueMap[FI] != NULL) 308 return false; 309 310 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) { 311 Value *OpF = IgnoreBitcasts(FI->getOperand(i)); 312 Value *OpG = IgnoreBitcasts(GI->getOperand(i)); 313 314 if (ValueMap[OpF] == OpG) 315 continue; 316 317 if (ValueMap[OpF] != NULL) 318 return false; 319 320 if (OpF->getValueID() != OpG->getValueID() || 321 !isEquivalentType(OpF->getType(), OpG->getType())) 322 return false; 323 324 if (isa<PHINode>(FI)) { 325 if (SpeculationMap[OpF] == NULL) 326 SpeculationMap[OpF] = OpG; 327 else if (SpeculationMap[OpF] != OpG) 328 return false; 329 continue; 330 } else if (isa<BasicBlock>(OpF)) { 331 assert(isa<TerminatorInst>(FI) && 332 "BasicBlock referenced by non-Terminator non-PHI"); 333 // This call changes the ValueMap, hence we can't use 334 // Value *& = ValueMap[...] 335 if (!equals(cast<BasicBlock>(OpF), cast<BasicBlock>(OpG), ValueMap, 336 SpeculationMap)) 337 return false; 338 } else { 339 if (!compare(OpF, OpG)) 340 return false; 341 } 342 343 ValueMap[OpF] = OpG; 344 } 345 346 ValueMap[FI] = GI; 347 ++FI, ++GI; 348 } while (FI != FE && GI != GE); 349 350 return FI == FE && GI == GE; 351 } 352 353 static bool equals(const Function *F, const Function *G) { 354 // We need to recheck everything, but check the things that weren't included 355 // in the hash first. 356 357 if (F->getAttributes() != G->getAttributes()) 358 return false; 359 360 if (F->hasGC() != G->hasGC()) 361 return false; 362 363 if (F->hasGC() && F->getGC() != G->getGC()) 364 return false; 365 366 if (F->hasSection() != G->hasSection()) 367 return false; 368 369 if (F->hasSection() && F->getSection() != G->getSection()) 370 return false; 371 372 if (F->isVarArg() != G->isVarArg()) 373 return false; 374 375 // TODO: if it's internal and only used in direct calls, we could handle this 376 // case too. 377 if (F->getCallingConv() != G->getCallingConv()) 378 return false; 379 380 if (!isEquivalentType(F->getFunctionType(), G->getFunctionType())) 381 return false; 382 383 DenseMap<const Value *, const Value *> ValueMap; 384 DenseMap<const Value *, const Value *> SpeculationMap; 385 ValueMap[F] = G; 386 387 assert(F->arg_size() == G->arg_size() && 388 "Identical functions have a different number of args."); 389 390 for (Function::const_arg_iterator fi = F->arg_begin(), gi = G->arg_begin(), 391 fe = F->arg_end(); fi != fe; ++fi, ++gi) 392 ValueMap[fi] = gi; 393 394 if (!equals(&F->getEntryBlock(), &G->getEntryBlock(), ValueMap, 395 SpeculationMap)) 396 return false; 397 398 for (DenseMap<const Value *, const Value *>::iterator 399 I = SpeculationMap.begin(), E = SpeculationMap.end(); I != E; ++I) { 400 if (ValueMap[I->first] != I->second) 401 return false; 402 } 403 404 return true; 405 } 406 407 // ===----------------------------------------------------------------------=== 408 // Folding of functions 409 // ===----------------------------------------------------------------------=== 410 411 // Cases: 412 // * F is external strong, G is external strong: 413 // turn G into a thunk to F (1) 414 // * F is external strong, G is external weak: 415 // turn G into a thunk to F (1) 416 // * F is external weak, G is external weak: 417 // unfoldable 418 // * F is external strong, G is internal: 419 // address of G taken: 420 // turn G into a thunk to F (1) 421 // address of G not taken: 422 // make G an alias to F (2) 423 // * F is internal, G is external weak 424 // address of F is taken: 425 // turn G into a thunk to F (1) 426 // address of F is not taken: 427 // make G an alias of F (2) 428 // * F is internal, G is internal: 429 // address of F and G are taken: 430 // turn G into a thunk to F (1) 431 // address of G is not taken: 432 // make G an alias to F (2) 433 // 434 // alias requires linkage == (external,local,weak) fallback to creating a thunk 435 // external means 'externally visible' linkage != (internal,private) 436 // internal means linkage == (internal,private) 437 // weak means linkage mayBeOverridable 438 // being external implies that the address is taken 439 // 440 // 1. turn G into a thunk to F 441 // 2. make G an alias to F 442 443 enum LinkageCategory { 444 ExternalStrong, 445 ExternalWeak, 446 Internal 447 }; 448 449 static LinkageCategory categorize(const Function *F) { 450 switch (F->getLinkage()) { 451 case GlobalValue::InternalLinkage: 452 case GlobalValue::PrivateLinkage: 453 return Internal; 454 455 case GlobalValue::WeakAnyLinkage: 456 case GlobalValue::WeakODRLinkage: 457 case GlobalValue::ExternalWeakLinkage: 458 return ExternalWeak; 459 460 case GlobalValue::ExternalLinkage: 461 case GlobalValue::AvailableExternallyLinkage: 462 case GlobalValue::LinkOnceAnyLinkage: 463 case GlobalValue::LinkOnceODRLinkage: 464 case GlobalValue::AppendingLinkage: 465 case GlobalValue::DLLImportLinkage: 466 case GlobalValue::DLLExportLinkage: 467 case GlobalValue::GhostLinkage: 468 case GlobalValue::CommonLinkage: 469 return ExternalStrong; 470 } 471 472 assert(0 && "Unknown LinkageType."); 473 return ExternalWeak; 474 } 475 476 static void ThunkGToF(Function *F, Function *G) { 477 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "", 478 G->getParent()); 479 BasicBlock *BB = BasicBlock::Create("", NewG); 480 481 std::vector<Value *> Args; 482 unsigned i = 0; 483 const FunctionType *FFTy = F->getFunctionType(); 484 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end(); 485 AI != AE; ++AI) { 486 if (FFTy->getParamType(i) == AI->getType()) 487 Args.push_back(AI); 488 else { 489 Value *BCI = new BitCastInst(AI, FFTy->getParamType(i), "", BB); 490 Args.push_back(BCI); 491 } 492 ++i; 493 } 494 495 CallInst *CI = CallInst::Create(F, Args.begin(), Args.end(), "", BB); 496 CI->setTailCall(); 497 CI->setCallingConv(F->getCallingConv()); 498 if (NewG->getReturnType() == Type::VoidTy) { 499 ReturnInst::Create(BB); 500 } else if (CI->getType() != NewG->getReturnType()) { 501 Value *BCI = new BitCastInst(CI, NewG->getReturnType(), "", BB); 502 ReturnInst::Create(BCI, BB); 503 } else { 504 ReturnInst::Create(CI, BB); 505 } 506 507 NewG->copyAttributesFrom(G); 508 NewG->takeName(G); 509 G->replaceAllUsesWith(NewG); 510 G->eraseFromParent(); 511 512 // TODO: look at direct callers to G and make them all direct callers to F. 513 } 514 515 static void AliasGToF(Function *F, Function *G) { 516 if (!G->hasExternalLinkage() && !G->hasLocalLinkage() && !G->hasWeakLinkage()) 517 return ThunkGToF(F, G); 518 519 GlobalAlias *GA = new GlobalAlias( 520 G->getType(), G->getLinkage(), "", 521 F->getContext()->getConstantExprBitCast(F, G->getType()), G->getParent()); 522 F->setAlignment(std::max(F->getAlignment(), G->getAlignment())); 523 GA->takeName(G); 524 GA->setVisibility(G->getVisibility()); 525 G->replaceAllUsesWith(GA); 526 G->eraseFromParent(); 527 } 528 529 static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) { 530 Function *F = FnVec[i]; 531 Function *G = FnVec[j]; 532 533 LinkageCategory catF = categorize(F); 534 LinkageCategory catG = categorize(G); 535 536 if (catF == ExternalWeak || (catF == Internal && catG == ExternalStrong)) { 537 std::swap(FnVec[i], FnVec[j]); 538 std::swap(F, G); 539 std::swap(catF, catG); 540 } 541 542 switch (catF) { 543 case ExternalStrong: 544 switch (catG) { 545 case ExternalStrong: 546 case ExternalWeak: 547 ThunkGToF(F, G); 548 break; 549 case Internal: 550 if (G->hasAddressTaken()) 551 ThunkGToF(F, G); 552 else 553 AliasGToF(F, G); 554 break; 555 } 556 break; 557 558 case ExternalWeak: { 559 assert(catG == ExternalWeak); 560 561 // Make them both thunks to the same internal function. 562 F->setAlignment(std::max(F->getAlignment(), G->getAlignment())); 563 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "", 564 F->getParent()); 565 H->copyAttributesFrom(F); 566 H->takeName(F); 567 F->replaceAllUsesWith(H); 568 569 ThunkGToF(F, G); 570 ThunkGToF(F, H); 571 572 F->setLinkage(GlobalValue::InternalLinkage); 573 } break; 574 575 case Internal: 576 switch (catG) { 577 case ExternalStrong: 578 assert(0); 579 // fall-through 580 case ExternalWeak: 581 if (F->hasAddressTaken()) 582 ThunkGToF(F, G); 583 else 584 AliasGToF(F, G); 585 break; 586 case Internal: { 587 bool addrTakenF = F->hasAddressTaken(); 588 bool addrTakenG = G->hasAddressTaken(); 589 if (!addrTakenF && addrTakenG) { 590 std::swap(FnVec[i], FnVec[j]); 591 std::swap(F, G); 592 std::swap(addrTakenF, addrTakenG); 593 } 594 595 if (addrTakenF && addrTakenG) { 596 ThunkGToF(F, G); 597 } else { 598 assert(!addrTakenG); 599 AliasGToF(F, G); 600 } 601 } break; 602 } 603 break; 604 } 605 606 ++NumFunctionsMerged; 607 return true; 608 } 609 610 // ===----------------------------------------------------------------------=== 611 // Pass definition 612 // ===----------------------------------------------------------------------=== 613 614 bool MergeFunctions::runOnModule(Module &M) { 615 bool Changed = false; 616 617 std::map<unsigned long, std::vector<Function *> > FnMap; 618 619 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) { 620 if (F->isDeclaration() || F->isIntrinsic()) 621 continue; 622 623 FnMap[hash(F)].push_back(F); 624 } 625 626 // TODO: instead of running in a loop, we could also fold functions in 627 // callgraph order. Constructing the CFG probably isn't cheaper than just 628 // running in a loop, unless it happened to already be available. 629 630 bool LocalChanged; 631 do { 632 LocalChanged = false; 633 DOUT << "size: " << FnMap.size() << "\n"; 634 for (std::map<unsigned long, std::vector<Function *> >::iterator 635 I = FnMap.begin(), E = FnMap.end(); I != E; ++I) { 636 std::vector<Function *> &FnVec = I->second; 637 DOUT << "hash (" << I->first << "): " << FnVec.size() << "\n"; 638 639 for (int i = 0, e = FnVec.size(); i != e; ++i) { 640 for (int j = i + 1; j != e; ++j) { 641 bool isEqual = equals(FnVec[i], FnVec[j]); 642 643 DOUT << " " << FnVec[i]->getName() 644 << (isEqual ? " == " : " != ") 645 << FnVec[j]->getName() << "\n"; 646 647 if (isEqual) { 648 if (fold(FnVec, i, j)) { 649 LocalChanged = true; 650 FnVec.erase(FnVec.begin() + j); 651 --j, --e; 652 } 653 } 654 } 655 } 656 657 } 658 Changed |= LocalChanged; 659 } while (LocalChanged); 660 661 return Changed; 662 } 663