LLVM API Documentation

MergeFunctions.cpp

Go to the documentation of this file.
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 Function will not be analyzed if:
00013 // * it is overridable at runtime (except for weak linkage), or
00014 // * it is used by anything other than the callee parameter of a call/invoke
00015 //
00016 // A hash is computed from the function, based on its type and number of
00017 // basic blocks.
00018 //
00019 // Once all hashes are computed, we perform an expensive equality comparison
00020 // on each function pair. This takes n^2/2 comparisons per bucket, so it's
00021 // important that the hash function be high quality. The equality comparison
00022 // iterates through each instruction in each basic block.
00023 //
00024 // When a match is found, the functions are folded. We can only fold two
00025 // functions when we know that the definition of one of them is not
00026 // overridable.
00027 // * fold a function marked internal by replacing all of its users.
00028 // * fold extern or weak functions by replacing them with a global alias
00029 //
00030 //===----------------------------------------------------------------------===//
00031 //
00032 // Future work:
00033 //
00034 // * fold vector<T*>::push_back and vector<S*>::push_back.
00035 //
00036 // These two functions have different types, but in a way that doesn't matter
00037 // to us. As long as we never see an S or T itself, using S* and S** is the
00038 // same as using a T* and T**.
00039 //
00040 // * virtual functions.
00041 //
00042 // Many functions have their address taken by the virtual function table for
00043 // the object they belong to. However, as long as it's only used for a lookup
00044 // and call, this is irrelevant, and we'd like to fold such implementations.
00045 //
00046 //===----------------------------------------------------------------------===//
00047 
00048 #define DEBUG_TYPE "mergefunc"
00049 #include "llvm/Transforms/IPO.h"
00050 #include "llvm/ADT/DenseMap.h"
00051 #include "llvm/ADT/Statistic.h"
00052 #include "llvm/Constants.h"
00053 #include "llvm/InlineAsm.h"
00054 #include "llvm/Instructions.h"
00055 #include "llvm/Module.h"
00056 #include "llvm/Pass.h"
00057 #include "llvm/Support/CallSite.h"
00058 #include "llvm/Support/Compiler.h"
00059 #include "llvm/Support/Debug.h"
00060 #include <map>
00061 #include <vector>
00062 using namespace llvm;
00063 
00064 STATISTIC(NumFunctionsMerged, "Number of functions merged");
00065 STATISTIC(NumMergeFails, "Number of identical function pairings not merged");
00066 
00067 namespace {
00068   struct VISIBILITY_HIDDEN MergeFunctions : public ModulePass {
00069     static char ID; // Pass identification, replacement for typeid
00070     MergeFunctions() : ModulePass((intptr_t)&ID) {}
00071 
00072     bool runOnModule(Module &M);
00073   };
00074 }
00075 
00076 char MergeFunctions::ID = 0;
00077 static RegisterPass<MergeFunctions>
00078 X("mergefunc", "Merge Functions");
00079 
00080 ModulePass *llvm::createMergeFunctionsPass() {
00081   return new MergeFunctions();
00082 }
00083 
00084 static unsigned long hash(const Function *F) {
00085   return F->size() ^ reinterpret_cast<unsigned long>(F->getType());
00086   //return F->size() ^ F->arg_size() ^ F->getReturnType();
00087 }
00088 
00089 static bool compare(const Value *V, const Value *U) {
00090   assert(!isa<BasicBlock>(V) && !isa<BasicBlock>(U) &&
00091          "Must not compare basic blocks.");
00092 
00093   assert(V->getType() == U->getType() &&
00094         "Two of the same operation have operands of different type.");
00095 
00096   // TODO: If the constant is an expression of F, we should accept that it's
00097   // equal to the same expression in terms of G.
00098   if (isa<Constant>(V))
00099     return V == U;
00100 
00101   // The caller has ensured that ValueMap[V] != U. Since Arguments are
00102   // pre-loaded into the ValueMap, and Instructions are added as we go, we know
00103   // that this can only be a mis-match.
00104   if (isa<Instruction>(V) || isa<Argument>(V))
00105     return false;
00106 
00107   if (isa<InlineAsm>(V) && isa<InlineAsm>(U)) {
00108     const InlineAsm *IAF = cast<InlineAsm>(V);
00109     const InlineAsm *IAG = cast<InlineAsm>(U);
00110     return IAF->getAsmString() == IAG->getAsmString() &&
00111            IAF->getConstraintString() == IAG->getConstraintString();
00112   }
00113 
00114   return false;
00115 }
00116 
00117 static bool equals(const BasicBlock *BB1, const BasicBlock *BB2,
00118                    DenseMap<const Value *, const Value *> &ValueMap,
00119                    DenseMap<const Value *, const Value *> &SpeculationMap) {
00120   // Specutively add it anyways. If it's false, we'll notice a difference later, and
00121   // this won't matter.
00122   ValueMap[BB1] = BB2;
00123 
00124   BasicBlock::const_iterator FI = BB1->begin(), FE = BB1->end();
00125   BasicBlock::const_iterator GI = BB2->begin(), GE = BB2->end();
00126 
00127   do {
00128     if (!FI->isSameOperationAs(const_cast<Instruction *>(&*GI)))
00129       return false;
00130 
00131     if (FI->getNumOperands() != GI->getNumOperands())
00132       return false;
00133 
00134     if (ValueMap[FI] == GI) {
00135       ++FI, ++GI;
00136       continue;
00137     }
00138 
00139     if (ValueMap[FI] != NULL)
00140       return false;
00141 
00142     for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
00143       Value *OpF = FI->getOperand(i);
00144       Value *OpG = GI->getOperand(i);
00145 
00146       if (ValueMap[OpF] == OpG)
00147         continue;
00148 
00149       if (ValueMap[OpF] != NULL)
00150         return false;
00151 
00152       assert(OpF->getType() == OpG->getType() &&
00153              "Two of the same operation has operands of different type.");
00154 
00155       if (OpF->getValueID() != OpG->getValueID())
00156         return false;
00157 
00158       if (isa<PHINode>(FI)) {
00159         if (SpeculationMap[OpF] == NULL)
00160           SpeculationMap[OpF] = OpG;
00161         else if (SpeculationMap[OpF] != OpG)
00162           return false;
00163         continue;
00164       } else if (isa<BasicBlock>(OpF)) {
00165         assert(isa<TerminatorInst>(FI) &&
00166                "BasicBlock referenced by non-Terminator non-PHI");
00167         // This call changes the ValueMap, hence we can't use
00168         // Value *& = ValueMap[...]
00169         if (!equals(cast<BasicBlock>(OpF), cast<BasicBlock>(OpG), ValueMap,
00170                     SpeculationMap))
00171           return false;
00172       } else {
00173         if (!compare(OpF, OpG))
00174           return false;
00175       }
00176 
00177       ValueMap[OpF] = OpG;
00178     }
00179 
00180     ValueMap[FI] = GI;
00181     ++FI, ++GI;
00182   } while (FI != FE && GI != GE);
00183 
00184   return FI == FE && GI == GE;
00185 }
00186 
00187 static bool equals(const Function *F, const Function *G) {
00188   // We need to recheck everything, but check the things that weren't included
00189   // in the hash first.
00190 
00191   if (F->getAttributes() != G->getAttributes())
00192     return false;
00193 
00194   if (F->hasGC() != G->hasGC())
00195     return false;
00196 
00197   if (F->hasGC() && F->getGC() != G->getGC())
00198     return false;
00199 
00200   if (F->hasSection() != G->hasSection())
00201     return false;
00202 
00203   if (F->hasSection() && F->getSection() != G->getSection())
00204     return false;
00205 
00206   // TODO: if it's internal and only used in direct calls, we could handle this
00207   // case too.
00208   if (F->getCallingConv() != G->getCallingConv())
00209     return false;
00210 
00211   // TODO: We want to permit cases where two functions take T* and S* but
00212   // only load or store them into T** and S**.
00213   if (F->getType() != G->getType())
00214     return false;
00215 
00216   DenseMap<const Value *, const Value *> ValueMap;
00217   DenseMap<const Value *, const Value *> SpeculationMap;
00218   ValueMap[F] = G;
00219 
00220   assert(F->arg_size() == G->arg_size() &&
00221          "Identical functions have a different number of args.");
00222 
00223   for (Function::const_arg_iterator fi = F->arg_begin(), gi = G->arg_begin(),
00224          fe = F->arg_end(); fi != fe; ++fi, ++gi)
00225     ValueMap[fi] = gi;
00226 
00227   if (!equals(&F->getEntryBlock(), &G->getEntryBlock(), ValueMap,
00228               SpeculationMap))
00229     return false;
00230 
00231   for (DenseMap<const Value *, const Value *>::iterator
00232          I = SpeculationMap.begin(), E = SpeculationMap.end(); I != E; ++I) {
00233     if (ValueMap[I->first] != I->second)
00234       return false;
00235   }
00236 
00237   return true;
00238 }
00239 
00240 static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) {
00241   if (FnVec[i]->mayBeOverridden() && !FnVec[j]->mayBeOverridden())
00242     std::swap(FnVec[i], FnVec[j]);
00243 
00244   Function *F = FnVec[i];
00245   Function *G = FnVec[j];
00246 
00247   if (!F->mayBeOverridden()) {
00248     if (G->hasLocalLinkage()) {
00249       F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
00250       G->replaceAllUsesWith(F);
00251       G->eraseFromParent();
00252       ++NumFunctionsMerged;
00253       return true;
00254     }
00255 
00256     if (G->hasExternalLinkage() || G->hasWeakLinkage()) {
00257       GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
00258                                         F, G->getParent());
00259       F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
00260       GA->takeName(G);
00261       GA->setVisibility(G->getVisibility());
00262       G->replaceAllUsesWith(GA);
00263       G->eraseFromParent();
00264       ++NumFunctionsMerged;
00265       return true;
00266     }
00267   }
00268 
00269   if (F->hasWeakLinkage() && G->hasWeakLinkage()) {
00270     GlobalAlias *GA_F = new GlobalAlias(F->getType(), F->getLinkage(), "",
00271                                         0, F->getParent());
00272     GA_F->takeName(F);
00273     GA_F->setVisibility(F->getVisibility());
00274     F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
00275     F->replaceAllUsesWith(GA_F);
00276     F->setName("folded." + GA_F->getName());
00277     F->setLinkage(GlobalValue::ExternalLinkage);
00278     GA_F->setAliasee(F);
00279 
00280     GlobalAlias *GA_G = new GlobalAlias(G->getType(), G->getLinkage(), "",
00281                                         F, G->getParent());
00282     GA_G->takeName(G);
00283     GA_G->setVisibility(G->getVisibility());
00284     G->replaceAllUsesWith(GA_G);
00285     G->eraseFromParent();
00286 
00287     ++NumFunctionsMerged;
00288     return true;
00289   }
00290 
00291   DOUT << "Failed on " << F->getName() << " and " << G->getName() << "\n";
00292 
00293   ++NumMergeFails;
00294   return false;
00295 }
00296 
00297 static bool hasAddressTaken(User *U) {
00298   for (User::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I) {
00299     User *Use = *I;
00300 
00301     // 'call (bitcast @F to ...)' happens a lot.
00302     while (isa<ConstantExpr>(Use) && Use->hasOneUse()) {
00303       Use = *Use->use_begin();
00304     }
00305 
00306     if (isa<ConstantExpr>(Use)) {
00307       if (hasAddressTaken(Use))
00308         return true;
00309     }
00310 
00311     if (!isa<CallInst>(Use) && !isa<InvokeInst>(Use))
00312       return true;
00313 
00314     // Make sure we aren't passing U as a parameter to call instead of the
00315     // callee.
00316     if (CallSite(cast<Instruction>(Use)).hasArgument(U))
00317       return true;
00318   }
00319 
00320   return false;
00321 }
00322 
00323 bool MergeFunctions::runOnModule(Module &M) {
00324   bool Changed = false;
00325 
00326   std::map<unsigned long, std::vector<Function *> > FnMap;
00327 
00328   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
00329     if (F->isDeclaration() || F->isIntrinsic())
00330       continue;
00331 
00332     if (!F->hasLocalLinkage() && !F->hasExternalLinkage() &&
00333         !F->hasWeakLinkage())
00334       continue;
00335 
00336     if (hasAddressTaken(F))
00337       continue;
00338 
00339     FnMap[hash(F)].push_back(F);
00340   }
00341 
00342   // TODO: instead of running in a loop, we could also fold functions in callgraph
00343   // order. Constructing the CFG probably isn't cheaper than just running in a loop.
00344 
00345   bool LocalChanged;
00346   do {
00347     LocalChanged = false;
00348     for (std::map<unsigned long, std::vector<Function *> >::iterator
00349          I = FnMap.begin(), E = FnMap.end(); I != E; ++I) {
00350       DOUT << "size: " << FnMap.size() << "\n";
00351       std::vector<Function *> &FnVec = I->second;
00352       DOUT << "hash (" << I->first << "): " << FnVec.size() << "\n";
00353 
00354       for (int i = 0, e = FnVec.size(); i != e; ++i) {
00355         for (int j = i + 1; j != e; ++j) {
00356           bool isEqual = equals(FnVec[i], FnVec[j]);
00357 
00358           DOUT << "  " << FnVec[i]->getName()
00359                << (isEqual ? " == " : " != ")
00360                << FnVec[j]->getName() << "\n";
00361 
00362           if (isEqual) {
00363             if (fold(FnVec, i, j)) {
00364               LocalChanged = true;
00365               FnVec.erase(FnVec.begin() + j);
00366               --j, --e;
00367             }
00368           }
00369         }
00370       }
00371 
00372     }
00373     Changed |= LocalChanged;
00374   } while (LocalChanged);
00375 
00376   return Changed;
00377 }