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