Unlike the other instructions, GEP really does need to look at the type of a
[oota-llvm.git] / lib / Transforms / IPO / MergeFunctions.cpp
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>
57 using namespace llvm;
58
59 STATISTIC(NumFunctionsMerged, "Number of functions merged");
60
61 namespace {
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
70 char MergeFunctions::ID = 0;
71 static RegisterPass<MergeFunctions>
72 X("mergefunc", "Merge Functions");
73
74 ModulePass *llvm::createMergeFunctionsPass() {
75   return new MergeFunctions();
76 }
77
78 // ===----------------------------------------------------------------------===
79 // Comparison of functions
80 // ===----------------------------------------------------------------------===
81
82 static 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.
98 static 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.
107 static 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::isSameOperationAs.
184 static bool
185 isEquivalentOperation(const Instruction *I1, const Instruction *I2) {
186   if (I1->getOpcode() != I2->getOpcode() ||
187       I1->getNumOperands() != I2->getNumOperands() ||
188       !isEquivalentType(I1->getType(), I2->getType()))
189     return false;
190
191   // We have two instructions of identical opcode and #operands.  Check to see
192   // if all operands are the same type
193   for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
194     if (!isEquivalentType(I1->getOperand(i)->getType(),
195                           I2->getOperand(i)->getType()))
196       return false;
197
198   // Check special state that is a part of some instructions.
199   if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
200     return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
201            LI->getAlignment() == cast<LoadInst>(I2)->getAlignment();
202   if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
203     return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
204            SI->getAlignment() == cast<StoreInst>(I2)->getAlignment();
205   if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
206     return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
207   if (const CallInst *CI = dyn_cast<CallInst>(I1))
208     return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
209            CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
210            CI->getAttributes().getRawPointer() ==
211              cast<CallInst>(I2)->getAttributes().getRawPointer();
212   if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
213     return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
214            CI->getAttributes().getRawPointer() ==
215              cast<InvokeInst>(I2)->getAttributes().getRawPointer();
216   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) {
217     if (IVI->getNumIndices() != cast<InsertValueInst>(I2)->getNumIndices())
218       return false;
219     for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i)
220       if (IVI->idx_begin()[i] != cast<InsertValueInst>(I2)->idx_begin()[i])
221         return false;
222     return true;
223   }
224   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) {
225     if (EVI->getNumIndices() != cast<ExtractValueInst>(I2)->getNumIndices())
226       return false;
227     for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i)
228       if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I2)->idx_begin()[i])
229         return false;
230     return true;
231   }
232
233   return true;
234 }
235
236 static bool compare(const Value *V, const Value *U) {
237   assert(!isa<BasicBlock>(V) && !isa<BasicBlock>(U) &&
238          "Must not compare basic blocks.");
239
240   assert(isEquivalentType(V->getType(), U->getType()) &&
241         "Two of the same operation have operands of different type.");
242
243   // TODO: If the constant is an expression of F, we should accept that it's
244   // equal to the same expression in terms of G.
245   if (isa<Constant>(V))
246     return V == U;
247
248   // The caller has ensured that ValueMap[V] != U. Since Arguments are
249   // pre-loaded into the ValueMap, and Instructions are added as we go, we know
250   // that this can only be a mis-match.
251   if (isa<Instruction>(V) || isa<Argument>(V))
252     return false;
253
254   if (isa<InlineAsm>(V) && isa<InlineAsm>(U)) {
255     const InlineAsm *IAF = cast<InlineAsm>(V);
256     const InlineAsm *IAG = cast<InlineAsm>(U);
257     return IAF->getAsmString() == IAG->getAsmString() &&
258            IAF->getConstraintString() == IAG->getConstraintString();
259   }
260
261   return false;
262 }
263
264 static bool equals(const BasicBlock *BB1, const BasicBlock *BB2,
265                    DenseMap<const Value *, const Value *> &ValueMap,
266                    DenseMap<const Value *, const Value *> &SpeculationMap) {
267   // Speculatively add it anyways. If it's false, we'll notice a difference
268   // later, and this won't matter.
269   ValueMap[BB1] = BB2;
270
271   BasicBlock::const_iterator FI = BB1->begin(), FE = BB1->end();
272   BasicBlock::const_iterator GI = BB2->begin(), GE = BB2->end();
273
274   do {
275     if (isa<BitCastInst>(FI)) {
276       ++FI;
277       continue;
278     }
279     if (isa<BitCastInst>(GI)) {
280       ++GI;
281       continue;
282     }
283
284     if (!isEquivalentOperation(FI, GI))
285       return false;
286
287     if (isa<GetElementPtrInst>(FI)) {
288       const GetElementPtrInst *GEPF = cast<GetElementPtrInst>(FI);
289       const GetElementPtrInst *GEPG = cast<GetElementPtrInst>(GI);
290       if (GEPF->hasAllZeroIndices() && GEPG->hasAllZeroIndices()) {
291         // It's effectively a bitcast.
292         ++FI, ++GI;
293         continue;
294       }
295
296       // TODO: we only really care about the elements before the index
297       if (FI->getOperand(0)->getType() != GI->getOperand(0)->getType())
298         return false;
299     }
300
301     if (ValueMap[FI] == GI) {
302       ++FI, ++GI;
303       continue;
304     }
305
306     if (ValueMap[FI] != NULL)
307       return false;
308
309     for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
310       Value *OpF = IgnoreBitcasts(FI->getOperand(i));
311       Value *OpG = IgnoreBitcasts(GI->getOperand(i));
312
313       if (ValueMap[OpF] == OpG)
314         continue;
315
316       if (ValueMap[OpF] != NULL)
317         return false;
318
319       if (OpF->getValueID() != OpG->getValueID() ||
320           !isEquivalentType(OpF->getType(), OpG->getType()))
321         return false;
322
323       if (isa<PHINode>(FI)) {
324         if (SpeculationMap[OpF] == NULL)
325           SpeculationMap[OpF] = OpG;
326         else if (SpeculationMap[OpF] != OpG)
327           return false;
328         continue;
329       } else if (isa<BasicBlock>(OpF)) {
330         assert(isa<TerminatorInst>(FI) &&
331                "BasicBlock referenced by non-Terminator non-PHI");
332         // This call changes the ValueMap, hence we can't use
333         // Value *& = ValueMap[...]
334         if (!equals(cast<BasicBlock>(OpF), cast<BasicBlock>(OpG), ValueMap,
335                     SpeculationMap))
336           return false;
337       } else {
338         if (!compare(OpF, OpG))
339           return false;
340       }
341
342       ValueMap[OpF] = OpG;
343     }
344
345     ValueMap[FI] = GI;
346     ++FI, ++GI;
347   } while (FI != FE && GI != GE);
348
349   return FI == FE && GI == GE;
350 }
351
352 static bool equals(const Function *F, const Function *G) {
353   // We need to recheck everything, but check the things that weren't included
354   // in the hash first.
355
356   if (F->getAttributes() != G->getAttributes())
357     return false;
358
359   if (F->hasGC() != G->hasGC())
360     return false;
361
362   if (F->hasGC() && F->getGC() != G->getGC())
363     return false;
364
365   if (F->hasSection() != G->hasSection())
366     return false;
367
368   if (F->hasSection() && F->getSection() != G->getSection())
369     return false;
370
371   if (F->isVarArg() != G->isVarArg())
372     return false;
373
374   // TODO: if it's internal and only used in direct calls, we could handle this
375   // case too.
376   if (F->getCallingConv() != G->getCallingConv())
377     return false;
378
379   if (!isEquivalentType(F->getFunctionType(), G->getFunctionType()))
380     return false;
381
382   DenseMap<const Value *, const Value *> ValueMap;
383   DenseMap<const Value *, const Value *> SpeculationMap;
384   ValueMap[F] = G;
385
386   assert(F->arg_size() == G->arg_size() &&
387          "Identical functions have a different number of args.");
388
389   for (Function::const_arg_iterator fi = F->arg_begin(), gi = G->arg_begin(),
390          fe = F->arg_end(); fi != fe; ++fi, ++gi)
391     ValueMap[fi] = gi;
392
393   if (!equals(&F->getEntryBlock(), &G->getEntryBlock(), ValueMap,
394               SpeculationMap))
395     return false;
396
397   for (DenseMap<const Value *, const Value *>::iterator
398          I = SpeculationMap.begin(), E = SpeculationMap.end(); I != E; ++I) {
399     if (ValueMap[I->first] != I->second)
400       return false;
401   }
402
403   return true;
404 }
405
406 // ===----------------------------------------------------------------------===
407 // Folding of functions
408 // ===----------------------------------------------------------------------===
409
410 // Cases:
411 // * F is external strong, G is external strong:
412 //   turn G into a thunk to F    (1)
413 // * F is external strong, G is external weak:
414 //   turn G into a thunk to F    (1)
415 // * F is external weak, G is external weak:
416 //   unfoldable
417 // * F is external strong, G is internal:
418 //   address of G taken:
419 //     turn G into a thunk to F  (1)
420 //   address of G not taken:
421 //     make G an alias to F      (2)
422 // * F is internal, G is external weak
423 //   address of F is taken:
424 //     turn G into a thunk to F  (1)
425 //   address of F is not taken:
426 //     make G an alias of F      (2)
427 // * F is internal, G is internal:
428 //   address of F and G are taken:
429 //     turn G into a thunk to F  (1)
430 //   address of G is not taken:
431 //     make G an alias to F      (2)
432 //
433 // alias requires linkage == (external,local,weak) fallback to creating a thunk
434 // external means 'externally visible' linkage != (internal,private)
435 // internal means linkage == (internal,private)
436 // weak means linkage mayBeOverridable
437 // being external implies that the address is taken
438 //
439 // 1. turn G into a thunk to F
440 // 2. make G an alias to F
441
442 enum LinkageCategory {
443   ExternalStrong,
444   ExternalWeak,
445   Internal
446 };
447
448 static LinkageCategory categorize(const Function *F) {
449   switch (F->getLinkage()) {
450   case GlobalValue::InternalLinkage:
451   case GlobalValue::PrivateLinkage:
452     return Internal;
453
454   case GlobalValue::WeakAnyLinkage:
455   case GlobalValue::WeakODRLinkage:
456   case GlobalValue::ExternalWeakLinkage:
457     return ExternalWeak;
458
459   case GlobalValue::ExternalLinkage:
460   case GlobalValue::AvailableExternallyLinkage:
461   case GlobalValue::LinkOnceAnyLinkage:
462   case GlobalValue::LinkOnceODRLinkage:
463   case GlobalValue::AppendingLinkage:
464   case GlobalValue::DLLImportLinkage:
465   case GlobalValue::DLLExportLinkage:
466   case GlobalValue::GhostLinkage:
467   case GlobalValue::CommonLinkage:
468     return ExternalStrong;
469   }
470
471   assert(0 && "Unknown LinkageType.");
472   return ExternalWeak;
473 }
474
475 static void ThunkGToF(Function *F, Function *G) {
476   Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
477                                     G->getParent());
478   BasicBlock *BB = BasicBlock::Create("", NewG);
479
480   std::vector<Value *> Args;
481   unsigned i = 0;
482   const FunctionType *FFTy = F->getFunctionType();
483   for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
484        AI != AE; ++AI) {
485     if (FFTy->getParamType(i) == AI->getType())
486       Args.push_back(AI);
487     else {
488       Value *BCI = new BitCastInst(AI, FFTy->getParamType(i), "", BB);
489       Args.push_back(BCI);
490     }
491     ++i;
492   }
493
494   CallInst *CI = CallInst::Create(F, Args.begin(), Args.end(), "", BB);
495   CI->setTailCall();
496   CI->setCallingConv(F->getCallingConv());
497   if (NewG->getReturnType() == Type::VoidTy) {
498     ReturnInst::Create(BB);
499   } else if (CI->getType() != NewG->getReturnType()) {
500     Value *BCI = new BitCastInst(CI, NewG->getReturnType(), "", BB);
501     ReturnInst::Create(BCI, BB);
502   } else {
503     ReturnInst::Create(CI, BB);
504   }
505
506   NewG->copyAttributesFrom(G);
507   NewG->takeName(G);
508   G->replaceAllUsesWith(NewG);
509   G->eraseFromParent();
510
511   // TODO: look at direct callers to G and make them all direct callers to F.
512 }
513
514 static void AliasGToF(Function *F, Function *G) {
515   if (!G->hasExternalLinkage() && !G->hasLocalLinkage() && !G->hasWeakLinkage())
516     return ThunkGToF(F, G);
517
518   GlobalAlias *GA = new GlobalAlias(
519     G->getType(), G->getLinkage(), "",
520     ConstantExpr::getBitCast(F, G->getType()), G->getParent());
521   F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
522   GA->takeName(G);
523   GA->setVisibility(G->getVisibility());
524   G->replaceAllUsesWith(GA);
525   G->eraseFromParent();
526 }
527
528 static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) {
529   Function *F = FnVec[i];
530   Function *G = FnVec[j];
531
532   LinkageCategory catF = categorize(F);
533   LinkageCategory catG = categorize(G);
534
535   if (catF == ExternalWeak || (catF == Internal && catG == ExternalStrong)) {
536     std::swap(FnVec[i], FnVec[j]);
537     std::swap(F, G);
538     std::swap(catF, catG);
539   }
540
541   switch (catF) {
542     case ExternalStrong:
543       switch (catG) {
544         case ExternalStrong:
545         case ExternalWeak:
546           ThunkGToF(F, G);
547           break;
548         case Internal:
549           if (G->hasAddressTaken())
550             ThunkGToF(F, G);
551           else
552             AliasGToF(F, G);
553           break;
554       }
555       break;
556
557     case ExternalWeak: {
558       assert(catG == ExternalWeak);
559
560       // Make them both thunks to the same internal function.
561       F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
562       Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
563                                      F->getParent());
564       H->copyAttributesFrom(F);
565       H->takeName(F);
566       F->replaceAllUsesWith(H);
567
568       ThunkGToF(F, G);
569       ThunkGToF(F, H);
570
571       F->setLinkage(GlobalValue::InternalLinkage);
572     } break;
573
574     case Internal:
575       switch (catG) {
576         case ExternalStrong:
577           assert(0);
578           // fall-through
579         case ExternalWeak:
580           if (F->hasAddressTaken())
581             ThunkGToF(F, G);
582           else
583             AliasGToF(F, G);
584           break;
585         case Internal: {
586           bool addrTakenF = F->hasAddressTaken();
587           bool addrTakenG = G->hasAddressTaken();
588           if (!addrTakenF && addrTakenG) {
589             std::swap(FnVec[i], FnVec[j]);
590             std::swap(F, G);
591             std::swap(addrTakenF, addrTakenG);
592           }
593
594           if (addrTakenF && addrTakenG) {
595             ThunkGToF(F, G);
596           } else {
597             assert(!addrTakenG);
598             AliasGToF(F, G);
599           }
600         } break;
601       }
602       break;
603   }
604
605   ++NumFunctionsMerged;
606   return true;
607 }
608
609 // ===----------------------------------------------------------------------===
610 // Pass definition
611 // ===----------------------------------------------------------------------===
612
613 bool MergeFunctions::runOnModule(Module &M) {
614   bool Changed = false;
615
616   std::map<unsigned long, std::vector<Function *> > FnMap;
617
618   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
619     if (F->isDeclaration() || F->isIntrinsic())
620       continue;
621
622     FnMap[hash(F)].push_back(F);
623   }
624
625   // TODO: instead of running in a loop, we could also fold functions in
626   // callgraph order. Constructing the CFG probably isn't cheaper than just
627   // running in a loop, unless it happened to already be available.
628
629   bool LocalChanged;
630   do {
631     LocalChanged = false;
632     DOUT << "size: " << FnMap.size() << "\n";
633     for (std::map<unsigned long, std::vector<Function *> >::iterator
634          I = FnMap.begin(), E = FnMap.end(); I != E; ++I) {
635       std::vector<Function *> &FnVec = I->second;
636       DOUT << "hash (" << I->first << "): " << FnVec.size() << "\n";
637
638       for (int i = 0, e = FnVec.size(); i != e; ++i) {
639         for (int j = i + 1; j != e; ++j) {
640           bool isEqual = equals(FnVec[i], FnVec[j]);
641
642           DOUT << "  " << FnVec[i]->getName()
643                << (isEqual ? " == " : " != ")
644                << FnVec[j]->getName() << "\n";
645
646           if (isEqual) {
647             if (fold(FnVec, i, j)) {
648               LocalChanged = true;
649               FnVec.erase(FnVec.begin() + j);
650               --j, --e;
651             }
652           }
653         }
654       }
655
656     }
657     Changed |= LocalChanged;
658   } while (LocalChanged);
659
660   return Changed;
661 }