1 //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass looks for equivalent functions that are mergable and folds them.
12 // A Function will not be analyzed if:
13 // * it is overridable at runtime (except for weak linkage), or
14 // * it is used by anything other than the callee parameter of a call/invoke
16 // A hash is computed from the function, based on its type and number of
19 // Once all hashes are computed, we perform an expensive equality comparison
20 // on each function pair. This takes n^2/2 comparisons per bucket, so it's
21 // important that the hash function be high quality. The equality comparison
22 // iterates through each instruction in each basic block.
24 // When a match is found, the functions are folded. We can only fold two
25 // functions when we know that the definition of one of them is not
27 // * fold a function marked internal by replacing all of its users.
28 // * fold extern or weak functions by replacing them with a global alias
30 //===----------------------------------------------------------------------===//
34 // * fold vector<T*>::push_back and vector<S*>::push_back.
36 // These two functions have different types, but in a way that doesn't matter
37 // to us. As long as we never see an S or T itself, using S* and S** is the
38 // same as using a T* and T**.
40 // * virtual functions.
42 // Many functions have their address taken by the virtual function table for
43 // the object they belong to. However, as long as it's only used for a lookup
44 // and call, this is irrelevant, and we'd like to fold such implementations.
46 //===----------------------------------------------------------------------===//
48 #define DEBUG_TYPE "mergefunc"
49 #include "llvm/Transforms/IPO.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/Statistic.h"
52 #include "llvm/Constants.h"
53 #include "llvm/InlineAsm.h"
54 #include "llvm/Instructions.h"
55 #include "llvm/Module.h"
56 #include "llvm/Pass.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/Debug.h"
63 STATISTIC(NumFunctionsMerged, "Number of functions merged");
64 STATISTIC(NumMergeFails, "Number of identical function pairings not merged");
67 struct VISIBILITY_HIDDEN MergeFunctions : public ModulePass {
68 static char ID; // Pass identification, replacement for typeid
69 MergeFunctions() : ModulePass((intptr_t)&ID) {}
71 bool runOnModule(Module &M);
75 char MergeFunctions::ID = 0;
76 static RegisterPass<MergeFunctions>
77 X("mergefunc", "Merge Functions");
79 ModulePass *llvm::createMergeFunctionsPass() {
80 return new MergeFunctions();
83 static unsigned long hash(const Function *F) {
84 return F->size() ^ reinterpret_cast<unsigned long>(F->getType());
85 //return F->size() ^ F->arg_size() ^ F->getReturnType();
88 static bool compare(const Value *V, const Value *U) {
89 assert(!isa<BasicBlock>(V) && !isa<BasicBlock>(U) &&
90 "Must not compare basic blocks.");
92 assert(V->getType() == U->getType() &&
93 "Two of the same operation have operands of different type.");
95 // TODO: If the constant is an expression of F, we should accept that it's
96 // equal to the same expression in terms of G.
100 // The caller has ensured that ValueMap[V] != U. Since Arguments are
101 // pre-loaded into the ValueMap, and Instructions are added as we go, we know
102 // that this can only be a mis-match.
103 if (isa<Instruction>(V) || isa<Argument>(V))
106 if (isa<InlineAsm>(V) && isa<InlineAsm>(U)) {
107 const InlineAsm *IAF = cast<InlineAsm>(V);
108 const InlineAsm *IAG = cast<InlineAsm>(U);
109 return IAF->getAsmString() == IAG->getAsmString() &&
110 IAF->getConstraintString() == IAG->getConstraintString();
116 static bool equals(const BasicBlock *BB1, const BasicBlock *BB2,
117 DenseMap<const Value *, const Value *> &ValueMap,
118 DenseMap<const Value *, const Value *> &SpeculationMap) {
119 // Specutively add it anyways. If it's false, we'll notice a difference later, and
120 // this won't matter.
123 BasicBlock::const_iterator FI = BB1->begin(), FE = BB1->end();
124 BasicBlock::const_iterator GI = BB2->begin(), GE = BB2->end();
127 if (!FI->isSameOperationAs(const_cast<Instruction *>(&*GI)))
130 if (FI->getNumOperands() != GI->getNumOperands())
133 if (ValueMap[FI] == GI) {
138 if (ValueMap[FI] != NULL)
141 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
142 Value *OpF = FI->getOperand(i);
143 Value *OpG = GI->getOperand(i);
145 if (ValueMap[OpF] == OpG)
148 if (ValueMap[OpF] != NULL)
151 assert(OpF->getType() == OpG->getType() &&
152 "Two of the same operation has operands of different type.");
154 if (OpF->getValueID() != OpG->getValueID())
157 if (isa<PHINode>(FI)) {
158 if (SpeculationMap[OpF] == NULL)
159 SpeculationMap[OpF] = OpG;
160 else if (SpeculationMap[OpF] != OpG)
163 } else if (isa<BasicBlock>(OpF)) {
164 assert(isa<TerminatorInst>(FI) &&
165 "BasicBlock referenced by non-Terminator non-PHI");
166 // This call changes the ValueMap, hence we can't use
167 // Value *& = ValueMap[...]
168 if (!equals(cast<BasicBlock>(OpF), cast<BasicBlock>(OpG), ValueMap,
172 if (!compare(OpF, OpG))
181 } while (FI != FE && GI != GE);
183 return FI == FE && GI == GE;
186 static bool equals(const Function *F, const Function *G) {
187 // We need to recheck everything, but check the things that weren't included
188 // in the hash first.
190 if (F->getAttributes() != G->getAttributes())
193 if (F->hasGC() != G->hasGC())
196 if (F->hasGC() && F->getGC() != G->getGC())
199 if (F->hasSection() != G->hasSection())
202 if (F->hasSection() && F->getSection() != G->getSection())
205 // TODO: if it's internal and only used in direct calls, we could handle this
207 if (F->getCallingConv() != G->getCallingConv())
210 // TODO: We want to permit cases where two functions take T* and S* but
211 // only load or store them into T** and S**.
212 if (F->getType() != G->getType())
215 DenseMap<const Value *, const Value *> ValueMap;
216 DenseMap<const Value *, const Value *> SpeculationMap;
219 assert(F->arg_size() == G->arg_size() &&
220 "Identical functions have a different number of args.");
222 for (Function::const_arg_iterator fi = F->arg_begin(), gi = G->arg_begin(),
223 fe = F->arg_end(); fi != fe; ++fi, ++gi)
226 if (!equals(&F->getEntryBlock(), &G->getEntryBlock(), ValueMap,
230 for (DenseMap<const Value *, const Value *>::iterator
231 I = SpeculationMap.begin(), E = SpeculationMap.end(); I != E; ++I) {
232 if (ValueMap[I->first] != I->second)
239 static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) {
240 if (FnVec[i]->mayBeOverridden() && !FnVec[j]->mayBeOverridden())
241 std::swap(FnVec[i], FnVec[j]);
243 Function *F = FnVec[i];
244 Function *G = FnVec[j];
246 if (!F->mayBeOverridden()) {
247 if (G->hasInternalLinkage()) {
248 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
249 G->replaceAllUsesWith(F);
250 G->eraseFromParent();
251 ++NumFunctionsMerged;
255 if (G->hasExternalLinkage() || G->hasWeakLinkage()) {
256 GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
258 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
260 GA->setVisibility(G->getVisibility());
261 G->replaceAllUsesWith(GA);
262 G->eraseFromParent();
263 ++NumFunctionsMerged;
268 DOUT << "Failed on " << F->getName() << " and " << G->getName() << "\n";
274 static bool hasAddressTaken(User *U) {
275 for (User::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I) {
278 // 'call (bitcast @F to ...)' happens a lot.
279 while (isa<ConstantExpr>(Use) && Use->hasOneUse()) {
280 Use = *Use->use_begin();
283 if (isa<ConstantExpr>(Use)) {
284 if (hasAddressTaken(Use))
288 if (!isa<CallInst>(Use) && !isa<InvokeInst>(Use))
291 // Make sure we aren't passing U as a parameter to call instead of the
292 // callee. getOperand(0) is the callee for both CallInst and InvokeInst.
293 // Check the other operands to see if any of them is F.
294 for (User::op_iterator OI = I->op_begin() + 1, OE = I->op_end(); OI != OE;
304 bool MergeFunctions::runOnModule(Module &M) {
305 bool Changed = false;
307 std::map<unsigned long, std::vector<Function *> > FnMap;
309 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
310 if (F->isDeclaration() || F->isIntrinsic())
313 if (F->hasLinkOnceLinkage() || F->hasCommonLinkage() ||
314 F->hasDLLImportLinkage() || F->hasDLLExportLinkage())
317 if (hasAddressTaken(F))
320 FnMap[hash(F)].push_back(F);
323 // TODO: instead of running in a loop, we could also fold functions in callgraph
324 // order. Constructing the CFG probably isn't cheaper than just running in a loop.
328 LocalChanged = false;
329 for (std::map<unsigned long, std::vector<Function *> >::iterator
330 I = FnMap.begin(), E = FnMap.end(); I != E; ++I) {
331 DOUT << "size: " << FnMap.size() << "\n";
332 std::vector<Function *> &FnVec = I->second;
333 DOUT << "hash (" << I->first << "): " << FnVec.size() << "\n";
335 for (int i = 0, e = FnVec.size(); i != e; ++i) {
336 for (int j = i + 1; j != e; ++j) {
337 bool isEqual = equals(FnVec[i], FnVec[j]);
339 DOUT << " " << FnVec[i]->getName()
340 << (isEqual ? " == " : " != ")
341 << FnVec[j]->getName() << "\n";
344 if (fold(FnVec, i, j)) {
346 FnVec.erase(FnVec.begin() + j);
354 Changed |= LocalChanged;
355 } while (LocalChanged);