LLVM API Documentation
00001 //===- MergeFunctions.cpp - Merge identical functions ---------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This pass looks for equivalent functions that are mergable and folds them. 00011 // 00012 // A hash is computed from the function, based on its type and number of 00013 // basic blocks. 00014 // 00015 // Once all hashes are computed, we perform an expensive equality comparison 00016 // on each function pair. This takes n^2/2 comparisons per bucket, so it's 00017 // important that the hash function be high quality. The equality comparison 00018 // iterates through each instruction in each basic block. 00019 // 00020 // When a match is found the functions are folded. If both functions are 00021 // overridable, we move the functionality into a new internal function and 00022 // leave two overridable thunks to it. 00023 // 00024 //===----------------------------------------------------------------------===// 00025 // 00026 // Future work: 00027 // 00028 // * virtual functions. 00029 // 00030 // Many functions have their address taken by the virtual function table for 00031 // the object they belong to. However, as long as it's only used for a lookup 00032 // and call, this is irrelevant, and we'd like to fold such functions. 00033 // 00034 // * switch from n^2 pair-wise comparisons to an n-way comparison for each 00035 // bucket. 00036 // 00037 // * be smarter about bitcasts. 00038 // 00039 // In order to fold functions, we will sometimes add either bitcast instructions 00040 // or bitcast constant expressions. Unfortunately, this can confound further 00041 // analysis since the two functions differ where one has a bitcast and the 00042 // other doesn't. We should learn to look through bitcasts. 00043 // 00044 //===----------------------------------------------------------------------===// 00045 00046 #define DEBUG_TYPE "mergefunc" 00047 #include "llvm/Transforms/IPO.h" 00048 #include "llvm/ADT/DenseSet.h" 00049 #include "llvm/ADT/FoldingSet.h" 00050 #include "llvm/ADT/STLExtras.h" 00051 #include "llvm/ADT/SmallSet.h" 00052 #include "llvm/ADT/Statistic.h" 00053 #include "llvm/IR/Constants.h" 00054 #include "llvm/IR/DataLayout.h" 00055 #include "llvm/IR/IRBuilder.h" 00056 #include "llvm/IR/InlineAsm.h" 00057 #include "llvm/IR/Instructions.h" 00058 #include "llvm/IR/LLVMContext.h" 00059 #include "llvm/IR/Module.h" 00060 #include "llvm/IR/Operator.h" 00061 #include "llvm/Pass.h" 00062 #include "llvm/Support/CallSite.h" 00063 #include "llvm/Support/Debug.h" 00064 #include "llvm/Support/ErrorHandling.h" 00065 #include "llvm/Support/ValueHandle.h" 00066 #include "llvm/Support/raw_ostream.h" 00067 #include <vector> 00068 using namespace llvm; 00069 00070 STATISTIC(NumFunctionsMerged, "Number of functions merged"); 00071 STATISTIC(NumThunksWritten, "Number of thunks generated"); 00072 STATISTIC(NumAliasesWritten, "Number of aliases generated"); 00073 STATISTIC(NumDoubleWeak, "Number of new functions created"); 00074 00075 /// Returns the type id for a type to be hashed. We turn pointer types into 00076 /// integers here because the actual compare logic below considers pointers and 00077 /// integers of the same size as equal. 00078 static Type::TypeID getTypeIDForHash(Type *Ty) { 00079 if (Ty->isPointerTy()) 00080 return Type::IntegerTyID; 00081 return Ty->getTypeID(); 00082 } 00083 00084 /// Creates a hash-code for the function which is the same for any two 00085 /// functions that will compare equal, without looking at the instructions 00086 /// inside the function. 00087 static unsigned profileFunction(const Function *F) { 00088 FunctionType *FTy = F->getFunctionType(); 00089 00090 FoldingSetNodeID ID; 00091 ID.AddInteger(F->size()); 00092 ID.AddInteger(F->getCallingConv()); 00093 ID.AddBoolean(F->hasGC()); 00094 ID.AddBoolean(FTy->isVarArg()); 00095 ID.AddInteger(getTypeIDForHash(FTy->getReturnType())); 00096 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 00097 ID.AddInteger(getTypeIDForHash(FTy->getParamType(i))); 00098 return ID.ComputeHash(); 00099 } 00100 00101 namespace { 00102 00103 /// ComparableFunction - A struct that pairs together functions with a 00104 /// DataLayout so that we can keep them together as elements in the DenseSet. 00105 class ComparableFunction { 00106 public: 00107 static const ComparableFunction EmptyKey; 00108 static const ComparableFunction TombstoneKey; 00109 static DataLayout * const LookupOnly; 00110 00111 ComparableFunction(Function *Func, DataLayout *TD) 00112 : Func(Func), Hash(profileFunction(Func)), TD(TD) {} 00113 00114 Function *getFunc() const { return Func; } 00115 unsigned getHash() const { return Hash; } 00116 DataLayout *getTD() const { return TD; } 00117 00118 // Drops AssertingVH reference to the function. Outside of debug mode, this 00119 // does nothing. 00120 void release() { 00121 assert(Func && 00122 "Attempted to release function twice, or release empty/tombstone!"); 00123 Func = NULL; 00124 } 00125 00126 private: 00127 explicit ComparableFunction(unsigned Hash) 00128 : Func(NULL), Hash(Hash), TD(NULL) {} 00129 00130 AssertingVH<Function> Func; 00131 unsigned Hash; 00132 DataLayout *TD; 00133 }; 00134 00135 const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0); 00136 const ComparableFunction ComparableFunction::TombstoneKey = 00137 ComparableFunction(1); 00138 DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1); 00139 00140 } 00141 00142 namespace llvm { 00143 template <> 00144 struct DenseMapInfo<ComparableFunction> { 00145 static ComparableFunction getEmptyKey() { 00146 return ComparableFunction::EmptyKey; 00147 } 00148 static ComparableFunction getTombstoneKey() { 00149 return ComparableFunction::TombstoneKey; 00150 } 00151 static unsigned getHashValue(const ComparableFunction &CF) { 00152 return CF.getHash(); 00153 } 00154 static bool isEqual(const ComparableFunction &LHS, 00155 const ComparableFunction &RHS); 00156 }; 00157 } 00158 00159 namespace { 00160 00161 /// FunctionComparator - Compares two functions to determine whether or not 00162 /// they will generate machine code with the same behaviour. DataLayout is 00163 /// used if available. The comparator always fails conservatively (erring on the 00164 /// side of claiming that two functions are different). 00165 class FunctionComparator { 00166 public: 00167 FunctionComparator(const DataLayout *TD, const Function *F1, 00168 const Function *F2) 00169 : F1(F1), F2(F2), TD(TD) {} 00170 00171 /// Test whether the two functions have equivalent behaviour. 00172 bool compare(); 00173 00174 private: 00175 /// Test whether two basic blocks have equivalent behaviour. 00176 bool compare(const BasicBlock *BB1, const BasicBlock *BB2); 00177 00178 /// Assign or look up previously assigned numbers for the two values, and 00179 /// return whether the numbers are equal. Numbers are assigned in the order 00180 /// visited. 00181 bool enumerate(const Value *V1, const Value *V2); 00182 00183 /// Compare two Instructions for equivalence, similar to 00184 /// Instruction::isSameOperationAs but with modifications to the type 00185 /// comparison. 00186 bool isEquivalentOperation(const Instruction *I1, 00187 const Instruction *I2) const; 00188 00189 /// Compare two GEPs for equivalent pointer arithmetic. 00190 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2); 00191 bool isEquivalentGEP(const GetElementPtrInst *GEP1, 00192 const GetElementPtrInst *GEP2) { 00193 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2)); 00194 } 00195 00196 /// Compare two Types, treating all pointer types as equal. 00197 bool isEquivalentType(Type *Ty1, Type *Ty2) const; 00198 00199 // The two functions undergoing comparison. 00200 const Function *F1, *F2; 00201 00202 const DataLayout *TD; 00203 00204 DenseMap<const Value *, const Value *> id_map; 00205 DenseSet<const Value *> seen_values; 00206 }; 00207 00208 } 00209 00210 // Any two pointers in the same address space are equivalent, intptr_t and 00211 // pointers are equivalent. Otherwise, standard type equivalence rules apply. 00212 bool FunctionComparator::isEquivalentType(Type *Ty1, Type *Ty2) const { 00213 if (Ty1 == Ty2) 00214 return true; 00215 if (Ty1->getTypeID() != Ty2->getTypeID()) { 00216 if (TD) { 00217 LLVMContext &Ctx = Ty1->getContext(); 00218 if (isa<PointerType>(Ty1) && Ty2 == TD->getIntPtrType(Ctx)) return true; 00219 if (isa<PointerType>(Ty2) && Ty1 == TD->getIntPtrType(Ctx)) return true; 00220 } 00221 return false; 00222 } 00223 00224 switch (Ty1->getTypeID()) { 00225 default: 00226 llvm_unreachable("Unknown type!"); 00227 // Fall through in Release mode. 00228 case Type::IntegerTyID: 00229 case Type::VectorTyID: 00230 // Ty1 == Ty2 would have returned true earlier. 00231 return false; 00232 00233 case Type::VoidTyID: 00234 case Type::FloatTyID: 00235 case Type::DoubleTyID: 00236 case Type::X86_FP80TyID: 00237 case Type::FP128TyID: 00238 case Type::PPC_FP128TyID: 00239 case Type::LabelTyID: 00240 case Type::MetadataTyID: 00241 return true; 00242 00243 case Type::PointerTyID: { 00244 PointerType *PTy1 = cast<PointerType>(Ty1); 00245 PointerType *PTy2 = cast<PointerType>(Ty2); 00246 return PTy1->getAddressSpace() == PTy2->getAddressSpace(); 00247 } 00248 00249 case Type::StructTyID: { 00250 StructType *STy1 = cast<StructType>(Ty1); 00251 StructType *STy2 = cast<StructType>(Ty2); 00252 if (STy1->getNumElements() != STy2->getNumElements()) 00253 return false; 00254 00255 if (STy1->isPacked() != STy2->isPacked()) 00256 return false; 00257 00258 for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) { 00259 if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i))) 00260 return false; 00261 } 00262 return true; 00263 } 00264 00265 case Type::FunctionTyID: { 00266 FunctionType *FTy1 = cast<FunctionType>(Ty1); 00267 FunctionType *FTy2 = cast<FunctionType>(Ty2); 00268 if (FTy1->getNumParams() != FTy2->getNumParams() || 00269 FTy1->isVarArg() != FTy2->isVarArg()) 00270 return false; 00271 00272 if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType())) 00273 return false; 00274 00275 for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) { 00276 if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i))) 00277 return false; 00278 } 00279 return true; 00280 } 00281 00282 case Type::ArrayTyID: { 00283 ArrayType *ATy1 = cast<ArrayType>(Ty1); 00284 ArrayType *ATy2 = cast<ArrayType>(Ty2); 00285 return ATy1->getNumElements() == ATy2->getNumElements() && 00286 isEquivalentType(ATy1->getElementType(), ATy2->getElementType()); 00287 } 00288 } 00289 } 00290 00291 // Determine whether the two operations are the same except that pointer-to-A 00292 // and pointer-to-B are equivalent. This should be kept in sync with 00293 // Instruction::isSameOperationAs. 00294 bool FunctionComparator::isEquivalentOperation(const Instruction *I1, 00295 const Instruction *I2) const { 00296 // Differences from Instruction::isSameOperationAs: 00297 // * replace type comparison with calls to isEquivalentType. 00298 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top 00299 // * because of the above, we don't test for the tail bit on calls later on 00300 if (I1->getOpcode() != I2->getOpcode() || 00301 I1->getNumOperands() != I2->getNumOperands() || 00302 !isEquivalentType(I1->getType(), I2->getType()) || 00303 !I1->hasSameSubclassOptionalData(I2)) 00304 return false; 00305 00306 // We have two instructions of identical opcode and #operands. Check to see 00307 // if all operands are the same type 00308 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i) 00309 if (!isEquivalentType(I1->getOperand(i)->getType(), 00310 I2->getOperand(i)->getType())) 00311 return false; 00312 00313 // Check special state that is a part of some instructions. 00314 if (const LoadInst *LI = dyn_cast<LoadInst>(I1)) 00315 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() && 00316 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() && 00317 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() && 00318 LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope(); 00319 if (const StoreInst *SI = dyn_cast<StoreInst>(I1)) 00320 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() && 00321 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() && 00322 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() && 00323 SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope(); 00324 if (const CmpInst *CI = dyn_cast<CmpInst>(I1)) 00325 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate(); 00326 if (const CallInst *CI = dyn_cast<CallInst>(I1)) 00327 return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() && 00328 CI->getAttributes() == cast<CallInst>(I2)->getAttributes(); 00329 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1)) 00330 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() && 00331 CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes(); 00332 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) 00333 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices(); 00334 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) 00335 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices(); 00336 if (const FenceInst *FI = dyn_cast<FenceInst>(I1)) 00337 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() && 00338 FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope(); 00339 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1)) 00340 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() && 00341 CXI->getOrdering() == cast<AtomicCmpXchgInst>(I2)->getOrdering() && 00342 CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope(); 00343 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1)) 00344 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() && 00345 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() && 00346 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() && 00347 RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope(); 00348 00349 return true; 00350 } 00351 00352 // Determine whether two GEP operations perform the same underlying arithmetic. 00353 bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1, 00354 const GEPOperator *GEP2) { 00355 // When we have target data, we can reduce the GEP down to the value in bytes 00356 // added to the address. 00357 unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 1; 00358 APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0); 00359 if (TD && 00360 GEP1->accumulateConstantOffset(*TD, Offset1) && 00361 GEP2->accumulateConstantOffset(*TD, Offset2)) { 00362 return Offset1 == Offset2; 00363 } 00364 00365 if (GEP1->getPointerOperand()->getType() != 00366 GEP2->getPointerOperand()->getType()) 00367 return false; 00368 00369 if (GEP1->getNumOperands() != GEP2->getNumOperands()) 00370 return false; 00371 00372 for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) { 00373 if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i))) 00374 return false; 00375 } 00376 00377 return true; 00378 } 00379 00380 // Compare two values used by the two functions under pair-wise comparison. If 00381 // this is the first time the values are seen, they're added to the mapping so 00382 // that we will detect mismatches on next use. 00383 bool FunctionComparator::enumerate(const Value *V1, const Value *V2) { 00384 // Check for function @f1 referring to itself and function @f2 referring to 00385 // itself, or referring to each other, or both referring to either of them. 00386 // They're all equivalent if the two functions are otherwise equivalent. 00387 if (V1 == F1 && V2 == F2) 00388 return true; 00389 if (V1 == F2 && V2 == F1) 00390 return true; 00391 00392 if (const Constant *C1 = dyn_cast<Constant>(V1)) { 00393 if (V1 == V2) return true; 00394 const Constant *C2 = dyn_cast<Constant>(V2); 00395 if (!C2) return false; 00396 // TODO: constant expressions with GEP or references to F1 or F2. 00397 if (C1->isNullValue() && C2->isNullValue() && 00398 isEquivalentType(C1->getType(), C2->getType())) 00399 return true; 00400 // Try bitcasting C2 to C1's type. If the bitcast is legal and returns C1 00401 // then they must have equal bit patterns. 00402 return C1->getType()->canLosslesslyBitCastTo(C2->getType()) && 00403 C1 == ConstantExpr::getBitCast(const_cast<Constant*>(C2), C1->getType()); 00404 } 00405 00406 if (isa<InlineAsm>(V1) || isa<InlineAsm>(V2)) 00407 return V1 == V2; 00408 00409 // Check that V1 maps to V2. If we find a value that V1 maps to then we simply 00410 // check whether it's equal to V2. When there is no mapping then we need to 00411 // ensure that V2 isn't already equivalent to something else. For this 00412 // purpose, we track the V2 values in a set. 00413 00414 const Value *&map_elem = id_map[V1]; 00415 if (map_elem) 00416 return map_elem == V2; 00417 if (!seen_values.insert(V2).second) 00418 return false; 00419 map_elem = V2; 00420 return true; 00421 } 00422 00423 // Test whether two basic blocks have equivalent behaviour. 00424 bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) { 00425 BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end(); 00426 BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end(); 00427 00428 do { 00429 if (!enumerate(F1I, F2I)) 00430 return false; 00431 00432 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) { 00433 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I); 00434 if (!GEP2) 00435 return false; 00436 00437 if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand())) 00438 return false; 00439 00440 if (!isEquivalentGEP(GEP1, GEP2)) 00441 return false; 00442 } else { 00443 if (!isEquivalentOperation(F1I, F2I)) 00444 return false; 00445 00446 assert(F1I->getNumOperands() == F2I->getNumOperands()); 00447 for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) { 00448 Value *OpF1 = F1I->getOperand(i); 00449 Value *OpF2 = F2I->getOperand(i); 00450 00451 if (!enumerate(OpF1, OpF2)) 00452 return false; 00453 00454 if (OpF1->getValueID() != OpF2->getValueID() || 00455 !isEquivalentType(OpF1->getType(), OpF2->getType())) 00456 return false; 00457 } 00458 } 00459 00460 ++F1I, ++F2I; 00461 } while (F1I != F1E && F2I != F2E); 00462 00463 return F1I == F1E && F2I == F2E; 00464 } 00465 00466 // Test whether the two functions have equivalent behaviour. 00467 bool FunctionComparator::compare() { 00468 // We need to recheck everything, but check the things that weren't included 00469 // in the hash first. 00470 00471 if (F1->getAttributes() != F2->getAttributes()) 00472 return false; 00473 00474 if (F1->hasGC() != F2->hasGC()) 00475 return false; 00476 00477 if (F1->hasGC() && F1->getGC() != F2->getGC()) 00478 return false; 00479 00480 if (F1->hasSection() != F2->hasSection()) 00481 return false; 00482 00483 if (F1->hasSection() && F1->getSection() != F2->getSection()) 00484 return false; 00485 00486 if (F1->isVarArg() != F2->isVarArg()) 00487 return false; 00488 00489 // TODO: if it's internal and only used in direct calls, we could handle this 00490 // case too. 00491 if (F1->getCallingConv() != F2->getCallingConv()) 00492 return false; 00493 00494 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType())) 00495 return false; 00496 00497 assert(F1->arg_size() == F2->arg_size() && 00498 "Identically typed functions have different numbers of args!"); 00499 00500 // Visit the arguments so that they get enumerated in the order they're 00501 // passed in. 00502 for (Function::const_arg_iterator f1i = F1->arg_begin(), 00503 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) { 00504 if (!enumerate(f1i, f2i)) 00505 llvm_unreachable("Arguments repeat!"); 00506 } 00507 00508 // We do a CFG-ordered walk since the actual ordering of the blocks in the 00509 // linked list is immaterial. Our walk starts at the entry block for both 00510 // functions, then takes each block from each terminator in order. As an 00511 // artifact, this also means that unreachable blocks are ignored. 00512 SmallVector<const BasicBlock *, 8> F1BBs, F2BBs; 00513 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1. 00514 00515 F1BBs.push_back(&F1->getEntryBlock()); 00516 F2BBs.push_back(&F2->getEntryBlock()); 00517 00518 VisitedBBs.insert(F1BBs[0]); 00519 while (!F1BBs.empty()) { 00520 const BasicBlock *F1BB = F1BBs.pop_back_val(); 00521 const BasicBlock *F2BB = F2BBs.pop_back_val(); 00522 00523 if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB)) 00524 return false; 00525 00526 const TerminatorInst *F1TI = F1BB->getTerminator(); 00527 const TerminatorInst *F2TI = F2BB->getTerminator(); 00528 00529 assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors()); 00530 for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) { 00531 if (!VisitedBBs.insert(F1TI->getSuccessor(i))) 00532 continue; 00533 00534 F1BBs.push_back(F1TI->getSuccessor(i)); 00535 F2BBs.push_back(F2TI->getSuccessor(i)); 00536 } 00537 } 00538 return true; 00539 } 00540 00541 namespace { 00542 00543 /// MergeFunctions finds functions which will generate identical machine code, 00544 /// by considering all pointer types to be equivalent. Once identified, 00545 /// MergeFunctions will fold them by replacing a call to one to a call to a 00546 /// bitcast of the other. 00547 /// 00548 class MergeFunctions : public ModulePass { 00549 public: 00550 static char ID; 00551 MergeFunctions() 00552 : ModulePass(ID), HasGlobalAliases(false) { 00553 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry()); 00554 } 00555 00556 bool runOnModule(Module &M); 00557 00558 private: 00559 typedef DenseSet<ComparableFunction> FnSetType; 00560 00561 /// A work queue of functions that may have been modified and should be 00562 /// analyzed again. 00563 std::vector<WeakVH> Deferred; 00564 00565 /// Insert a ComparableFunction into the FnSet, or merge it away if it's 00566 /// equal to one that's already present. 00567 bool insert(ComparableFunction &NewF); 00568 00569 /// Remove a Function from the FnSet and queue it up for a second sweep of 00570 /// analysis. 00571 void remove(Function *F); 00572 00573 /// Find the functions that use this Value and remove them from FnSet and 00574 /// queue the functions. 00575 void removeUsers(Value *V); 00576 00577 /// Replace all direct calls of Old with calls of New. Will bitcast New if 00578 /// necessary to make types match. 00579 void replaceDirectCallers(Function *Old, Function *New); 00580 00581 /// Merge two equivalent functions. Upon completion, G may be deleted, or may 00582 /// be converted into a thunk. In either case, it should never be visited 00583 /// again. 00584 void mergeTwoFunctions(Function *F, Function *G); 00585 00586 /// Replace G with a thunk or an alias to F. Deletes G. 00587 void writeThunkOrAlias(Function *F, Function *G); 00588 00589 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses 00590 /// of G with bitcast(F). Deletes G. 00591 void writeThunk(Function *F, Function *G); 00592 00593 /// Replace G with an alias to F. Deletes G. 00594 void writeAlias(Function *F, Function *G); 00595 00596 /// The set of all distinct functions. Use the insert() and remove() methods 00597 /// to modify it. 00598 FnSetType FnSet; 00599 00600 /// DataLayout for more accurate GEP comparisons. May be NULL. 00601 DataLayout *TD; 00602 00603 /// Whether or not the target supports global aliases. 00604 bool HasGlobalAliases; 00605 }; 00606 00607 } // end anonymous namespace 00608 00609 char MergeFunctions::ID = 0; 00610 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false) 00611 00612 ModulePass *llvm::createMergeFunctionsPass() { 00613 return new MergeFunctions(); 00614 } 00615 00616 bool MergeFunctions::runOnModule(Module &M) { 00617 bool Changed = false; 00618 TD = getAnalysisIfAvailable<DataLayout>(); 00619 00620 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { 00621 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) 00622 Deferred.push_back(WeakVH(I)); 00623 } 00624 FnSet.resize(Deferred.size()); 00625 00626 do { 00627 std::vector<WeakVH> Worklist; 00628 Deferred.swap(Worklist); 00629 00630 DEBUG(dbgs() << "size of module: " << M.size() << '\n'); 00631 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n'); 00632 00633 // Insert only strong functions and merge them. Strong function merging 00634 // always deletes one of them. 00635 for (std::vector<WeakVH>::iterator I = Worklist.begin(), 00636 E = Worklist.end(); I != E; ++I) { 00637 if (!*I) continue; 00638 Function *F = cast<Function>(*I); 00639 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() && 00640 !F->mayBeOverridden()) { 00641 ComparableFunction CF = ComparableFunction(F, TD); 00642 Changed |= insert(CF); 00643 } 00644 } 00645 00646 // Insert only weak functions and merge them. By doing these second we 00647 // create thunks to the strong function when possible. When two weak 00648 // functions are identical, we create a new strong function with two weak 00649 // weak thunks to it which are identical but not mergable. 00650 for (std::vector<WeakVH>::iterator I = Worklist.begin(), 00651 E = Worklist.end(); I != E; ++I) { 00652 if (!*I) continue; 00653 Function *F = cast<Function>(*I); 00654 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() && 00655 F->mayBeOverridden()) { 00656 ComparableFunction CF = ComparableFunction(F, TD); 00657 Changed |= insert(CF); 00658 } 00659 } 00660 DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n'); 00661 } while (!Deferred.empty()); 00662 00663 FnSet.clear(); 00664 00665 return Changed; 00666 } 00667 00668 bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS, 00669 const ComparableFunction &RHS) { 00670 if (LHS.getFunc() == RHS.getFunc() && 00671 LHS.getHash() == RHS.getHash()) 00672 return true; 00673 if (!LHS.getFunc() || !RHS.getFunc()) 00674 return false; 00675 00676 // One of these is a special "underlying pointer comparison only" object. 00677 if (LHS.getTD() == ComparableFunction::LookupOnly || 00678 RHS.getTD() == ComparableFunction::LookupOnly) 00679 return false; 00680 00681 assert(LHS.getTD() == RHS.getTD() && 00682 "Comparing functions for different targets"); 00683 00684 return FunctionComparator(LHS.getTD(), LHS.getFunc(), 00685 RHS.getFunc()).compare(); 00686 } 00687 00688 // Replace direct callers of Old with New. 00689 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) { 00690 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType()); 00691 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end(); 00692 UI != UE;) { 00693 Value::use_iterator TheIter = UI; 00694 ++UI; 00695 CallSite CS(*TheIter); 00696 if (CS && CS.isCallee(TheIter)) { 00697 remove(CS.getInstruction()->getParent()->getParent()); 00698 TheIter.getUse().set(BitcastNew); 00699 } 00700 } 00701 } 00702 00703 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G. 00704 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) { 00705 if (HasGlobalAliases && G->hasUnnamedAddr()) { 00706 if (G->hasExternalLinkage() || G->hasLocalLinkage() || 00707 G->hasWeakLinkage()) { 00708 writeAlias(F, G); 00709 return; 00710 } 00711 } 00712 00713 writeThunk(F, G); 00714 } 00715 00716 // Replace G with a simple tail call to bitcast(F). Also replace direct uses 00717 // of G with bitcast(F). Deletes G. 00718 void MergeFunctions::writeThunk(Function *F, Function *G) { 00719 if (!G->mayBeOverridden()) { 00720 // Redirect direct callers of G to F. 00721 replaceDirectCallers(G, F); 00722 } 00723 00724 // If G was internal then we may have replaced all uses of G with F. If so, 00725 // stop here and delete G. There's no need for a thunk. 00726 if (G->hasLocalLinkage() && G->use_empty()) { 00727 G->eraseFromParent(); 00728 return; 00729 } 00730 00731 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "", 00732 G->getParent()); 00733 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG); 00734 IRBuilder<false> Builder(BB); 00735 00736 SmallVector<Value *, 16> Args; 00737 unsigned i = 0; 00738 FunctionType *FFTy = F->getFunctionType(); 00739 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end(); 00740 AI != AE; ++AI) { 00741 Args.push_back(Builder.CreateBitCast(AI, FFTy->getParamType(i))); 00742 ++i; 00743 } 00744 00745 CallInst *CI = Builder.CreateCall(F, Args); 00746 CI->setTailCall(); 00747 CI->setCallingConv(F->getCallingConv()); 00748 if (NewG->getReturnType()->isVoidTy()) { 00749 Builder.CreateRetVoid(); 00750 } else { 00751 Type *RetTy = NewG->getReturnType(); 00752 if (CI->getType()->isIntegerTy() && RetTy->isPointerTy()) 00753 Builder.CreateRet(Builder.CreateIntToPtr(CI, RetTy)); 00754 else if (CI->getType()->isPointerTy() && RetTy->isIntegerTy()) 00755 Builder.CreateRet(Builder.CreatePtrToInt(CI, RetTy)); 00756 else 00757 Builder.CreateRet(Builder.CreateBitCast(CI, RetTy)); 00758 } 00759 00760 NewG->copyAttributesFrom(G); 00761 NewG->takeName(G); 00762 removeUsers(G); 00763 G->replaceAllUsesWith(NewG); 00764 G->eraseFromParent(); 00765 00766 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n'); 00767 ++NumThunksWritten; 00768 } 00769 00770 // Replace G with an alias to F and delete G. 00771 void MergeFunctions::writeAlias(Function *F, Function *G) { 00772 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType()); 00773 GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "", 00774 BitcastF, G->getParent()); 00775 F->setAlignment(std::max(F->getAlignment(), G->getAlignment())); 00776 GA->takeName(G); 00777 GA->setVisibility(G->getVisibility()); 00778 removeUsers(G); 00779 G->replaceAllUsesWith(GA); 00780 G->eraseFromParent(); 00781 00782 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n'); 00783 ++NumAliasesWritten; 00784 } 00785 00786 // Merge two equivalent functions. Upon completion, Function G is deleted. 00787 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) { 00788 if (F->mayBeOverridden()) { 00789 assert(G->mayBeOverridden()); 00790 00791 if (HasGlobalAliases) { 00792 // Make them both thunks to the same internal function. 00793 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "", 00794 F->getParent()); 00795 H->copyAttributesFrom(F); 00796 H->takeName(F); 00797 removeUsers(F); 00798 F->replaceAllUsesWith(H); 00799 00800 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment()); 00801 00802 writeAlias(F, G); 00803 writeAlias(F, H); 00804 00805 F->setAlignment(MaxAlignment); 00806 F->setLinkage(GlobalValue::PrivateLinkage); 00807 } else { 00808 // We can't merge them. Instead, pick one and update all direct callers 00809 // to call it and hope that we improve the instruction cache hit rate. 00810 replaceDirectCallers(G, F); 00811 } 00812 00813 ++NumDoubleWeak; 00814 } else { 00815 writeThunkOrAlias(F, G); 00816 } 00817 00818 ++NumFunctionsMerged; 00819 } 00820 00821 // Insert a ComparableFunction into the FnSet, or merge it away if equal to one 00822 // that was already inserted. 00823 bool MergeFunctions::insert(ComparableFunction &NewF) { 00824 std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF); 00825 if (Result.second) { 00826 DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n'); 00827 return false; 00828 } 00829 00830 const ComparableFunction &OldF = *Result.first; 00831 00832 // Never thunk a strong function to a weak function. 00833 assert(!OldF.getFunc()->mayBeOverridden() || 00834 NewF.getFunc()->mayBeOverridden()); 00835 00836 DEBUG(dbgs() << " " << OldF.getFunc()->getName() << " == " 00837 << NewF.getFunc()->getName() << '\n'); 00838 00839 Function *DeleteF = NewF.getFunc(); 00840 NewF.release(); 00841 mergeTwoFunctions(OldF.getFunc(), DeleteF); 00842 return true; 00843 } 00844 00845 // Remove a function from FnSet. If it was already in FnSet, add it to Deferred 00846 // so that we'll look at it in the next round. 00847 void MergeFunctions::remove(Function *F) { 00848 // We need to make sure we remove F, not a function "equal" to F per the 00849 // function equality comparator. 00850 // 00851 // The special "lookup only" ComparableFunction bypasses the expensive 00852 // function comparison in favour of a pointer comparison on the underlying 00853 // Function*'s. 00854 ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly); 00855 if (FnSet.erase(CF)) { 00856 DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n"); 00857 Deferred.push_back(F); 00858 } 00859 } 00860 00861 // For each instruction used by the value, remove() the function that contains 00862 // the instruction. This should happen right before a call to RAUW. 00863 void MergeFunctions::removeUsers(Value *V) { 00864 std::vector<Value *> Worklist; 00865 Worklist.push_back(V); 00866 while (!Worklist.empty()) { 00867 Value *V = Worklist.back(); 00868 Worklist.pop_back(); 00869 00870 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); 00871 UI != UE; ++UI) { 00872 Use &U = UI.getUse(); 00873 if (Instruction *I = dyn_cast<Instruction>(U.getUser())) { 00874 remove(I->getParent()->getParent()); 00875 } else if (isa<GlobalValue>(U.getUser())) { 00876 // do nothing 00877 } else if (Constant *C = dyn_cast<Constant>(U.getUser())) { 00878 for (Value::use_iterator CUI = C->use_begin(), CUE = C->use_end(); 00879 CUI != CUE; ++CUI) 00880 Worklist.push_back(*CUI); 00881 } 00882 } 00883 } 00884 }