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 hash is computed from the function, based on its type and number of
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.
20 // When a match is found the functions are folded. If both functions are
21 // overridable, we move the functionality into a new internal function and
22 // leave two overridable thunks to it.
24 //===----------------------------------------------------------------------===//
28 // * virtual functions.
30 // Many functions have their address taken by the virtual function table for
31 // the object they belong to. However, as long as it's only used for a lookup
32 // and call, this is irrelevant, and we'd like to fold such implementations.
34 // * switch from n^2 pair-wise comparisons to an n-way comparison for each
37 // * be smarter about bitcast.
39 // In order to fold functions, we will sometimes add either bitcast instructions
40 // or bitcast constant expressions. Unfortunately, this can confound further
41 // analysis since the two functions differ where one has a bitcast and the
42 // other doesn't. We should learn to peer through bitcasts without imposing bad
43 // performance properties.
45 // * emit aliases for ELF
47 // ELF supports symbol aliases which are represented with GlobalAlias in the
48 // Module, and we could emit them in the case that the addresses don't need to
49 // be distinct. The problem is that not all object formats support equivalent
50 // functionality. There's a few approaches to this problem;
51 // a) teach codegen to lower global aliases to thunks on platforms which don't
53 // b) always emit thunks, and create a separate thunk-to-alias pass which
54 // runs on ELF systems. This has the added benefit of transforming other
55 // thunks such as those produced by a C++ frontend into aliases when legal
58 //===----------------------------------------------------------------------===//
60 #define DEBUG_TYPE "mergefunc"
61 #include "llvm/Transforms/IPO.h"
62 #include "llvm/ADT/DenseMap.h"
63 #include "llvm/ADT/FoldingSet.h"
64 #include "llvm/ADT/SmallSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/Constants.h"
67 #include "llvm/InlineAsm.h"
68 #include "llvm/Instructions.h"
69 #include "llvm/LLVMContext.h"
70 #include "llvm/Module.h"
71 #include "llvm/Pass.h"
72 #include "llvm/Support/CallSite.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include "llvm/Target/TargetData.h"
81 STATISTIC(NumFunctionsMerged, "Number of functions merged");
84 /// MergeFunctions finds functions which will generate identical machine code,
85 /// by considering all pointer types to be equivalent. Once identified,
86 /// MergeFunctions will fold them by replacing a call to one to a call to a
87 /// bitcast of the other.
89 struct MergeFunctions : public ModulePass {
90 static char ID; // Pass identification, replacement for typeid
91 MergeFunctions() : ModulePass(ID) {}
93 bool runOnModule(Module &M);
97 char MergeFunctions::ID = 0;
98 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false);
100 ModulePass *llvm::createMergeFunctionsPass() {
101 return new MergeFunctions();
104 // ===----------------------------------------------------------------------===
105 // Comparison of functions
106 // ===----------------------------------------------------------------------===
108 class FunctionComparator {
110 FunctionComparator(TargetData *TD, Function *F1, Function *F2)
111 : F1(F1), F2(F2), TD(TD) {}
113 // Compare - test whether the two functions have equivalent behaviour.
117 // Compare - test whether two basic blocks have equivalent behaviour.
118 bool Compare(const BasicBlock *BB1, const BasicBlock *BB2);
120 // getDomain - a value's domain is its parent function if it is specific to a
121 // function, or NULL otherwise.
122 const Function *getDomain(const Value *V) const;
124 // Enumerate - Assign or look up previously assigned numbers for the two
125 // values, and return whether the numbers are equal. Numbers are assigned in
126 // the order visited.
127 bool Enumerate(const Value *V1, const Value *V2);
129 // isEquivalentOperation - Compare two Instructions for equivalence, similar
130 // to Instruction::isSameOperationAs but with modifications to the type
132 bool isEquivalentOperation(const Instruction *I1,
133 const Instruction *I2) const;
135 // isEquivalentGEP - Compare two GEPs for equivalent pointer arithmetic.
136 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
137 bool isEquivalentGEP(const GetElementPtrInst *GEP1,
138 const GetElementPtrInst *GEP2) {
139 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
142 // isEquivalentType - Compare two Types, treating all pointer types as equal.
143 bool isEquivalentType(const Type *Ty1, const Type *Ty2) const;
145 // The two functions undergoing comparison.
150 typedef DenseMap<const Value *, unsigned long> IDMap;
152 DenseMap<const Function *, IDMap> Domains;
153 DenseMap<const Function *, unsigned long> DomainCount;
157 /// Compute a number which is guaranteed to be equal for two equivalent
158 /// functions, but is very likely to be different for different functions. This
159 /// needs to be computed as efficiently as possible.
160 static unsigned long ProfileFunction(const Function *F) {
161 const FunctionType *FTy = F->getFunctionType();
164 ID.AddInteger(F->size());
165 ID.AddInteger(F->getCallingConv());
166 ID.AddBoolean(F->hasGC());
167 ID.AddBoolean(FTy->isVarArg());
168 ID.AddInteger(FTy->getReturnType()->getTypeID());
169 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
170 ID.AddInteger(FTy->getParamType(i)->getTypeID());
171 return ID.ComputeHash();
174 /// isEquivalentType - any two pointers are equivalent. Otherwise, standard
175 /// type equivalence rules apply.
176 bool FunctionComparator::isEquivalentType(const Type *Ty1,
177 const Type *Ty2) const {
180 if (Ty1->getTypeID() != Ty2->getTypeID())
183 switch(Ty1->getTypeID()) {
185 llvm_unreachable("Unknown type!");
186 // Fall through in Release mode.
187 case Type::IntegerTyID:
188 case Type::OpaqueTyID:
189 // Ty1 == Ty2 would have returned true earlier.
193 case Type::FloatTyID:
194 case Type::DoubleTyID:
195 case Type::X86_FP80TyID:
196 case Type::FP128TyID:
197 case Type::PPC_FP128TyID:
198 case Type::LabelTyID:
199 case Type::MetadataTyID:
202 case Type::PointerTyID: {
203 const PointerType *PTy1 = cast<PointerType>(Ty1);
204 const PointerType *PTy2 = cast<PointerType>(Ty2);
205 return PTy1->getAddressSpace() == PTy2->getAddressSpace();
208 case Type::StructTyID: {
209 const StructType *STy1 = cast<StructType>(Ty1);
210 const StructType *STy2 = cast<StructType>(Ty2);
211 if (STy1->getNumElements() != STy2->getNumElements())
214 if (STy1->isPacked() != STy2->isPacked())
217 for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) {
218 if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i)))
224 case Type::UnionTyID: {
225 const UnionType *UTy1 = cast<UnionType>(Ty1);
226 const UnionType *UTy2 = cast<UnionType>(Ty2);
228 // TODO: we could be fancy with union(A, union(A, B)) === union(A, B), etc.
229 if (UTy1->getNumElements() != UTy2->getNumElements())
232 for (unsigned i = 0, e = UTy1->getNumElements(); i != e; ++i) {
233 if (!isEquivalentType(UTy1->getElementType(i), UTy2->getElementType(i)))
239 case Type::FunctionTyID: {
240 const FunctionType *FTy1 = cast<FunctionType>(Ty1);
241 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
242 if (FTy1->getNumParams() != FTy2->getNumParams() ||
243 FTy1->isVarArg() != FTy2->isVarArg())
246 if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType()))
249 for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) {
250 if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i)))
256 case Type::ArrayTyID: {
257 const ArrayType *ATy1 = cast<ArrayType>(Ty1);
258 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
259 return ATy1->getNumElements() == ATy2->getNumElements() &&
260 isEquivalentType(ATy1->getElementType(), ATy2->getElementType());
262 case Type::VectorTyID: {
263 const VectorType *VTy1 = cast<VectorType>(Ty1);
264 const VectorType *VTy2 = cast<VectorType>(Ty2);
265 return VTy1->getNumElements() == VTy2->getNumElements() &&
266 isEquivalentType(VTy1->getElementType(), VTy2->getElementType());
271 /// isEquivalentOperation - determine whether the two operations are the same
272 /// except that pointer-to-A and pointer-to-B are equivalent. This should be
273 /// kept in sync with Instruction::isSameOperationAs.
274 bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
275 const Instruction *I2) const {
276 if (I1->getOpcode() != I2->getOpcode() ||
277 I1->getNumOperands() != I2->getNumOperands() ||
278 !isEquivalentType(I1->getType(), I2->getType()) ||
279 !I1->hasSameSubclassOptionalData(I2))
282 // We have two instructions of identical opcode and #operands. Check to see
283 // if all operands are the same type
284 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
285 if (!isEquivalentType(I1->getOperand(i)->getType(),
286 I2->getOperand(i)->getType()))
289 // Check special state that is a part of some instructions.
290 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
291 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
292 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment();
293 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
294 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
295 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment();
296 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
297 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
298 if (const CallInst *CI = dyn_cast<CallInst>(I1))
299 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
300 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
301 CI->getAttributes().getRawPointer() ==
302 cast<CallInst>(I2)->getAttributes().getRawPointer();
303 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
304 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
305 CI->getAttributes().getRawPointer() ==
306 cast<InvokeInst>(I2)->getAttributes().getRawPointer();
307 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) {
308 if (IVI->getNumIndices() != cast<InsertValueInst>(I2)->getNumIndices())
310 for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i)
311 if (IVI->idx_begin()[i] != cast<InsertValueInst>(I2)->idx_begin()[i])
315 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) {
316 if (EVI->getNumIndices() != cast<ExtractValueInst>(I2)->getNumIndices())
318 for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i)
319 if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I2)->idx_begin()[i])
327 /// isEquivalentGEP - determine whether two GEP operations perform the same
328 /// underlying arithmetic.
329 bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
330 const GEPOperator *GEP2) {
331 // When we have target data, we can reduce the GEP down to the value in bytes
332 // added to the address.
333 if (TD && GEP1->hasAllConstantIndices() && GEP2->hasAllConstantIndices()) {
334 SmallVector<Value *, 8> Indices1(GEP1->idx_begin(), GEP1->idx_end());
335 SmallVector<Value *, 8> Indices2(GEP2->idx_begin(), GEP2->idx_end());
336 uint64_t Offset1 = TD->getIndexedOffset(GEP1->getPointerOperandType(),
337 Indices1.data(), Indices1.size());
338 uint64_t Offset2 = TD->getIndexedOffset(GEP2->getPointerOperandType(),
339 Indices2.data(), Indices2.size());
340 return Offset1 == Offset2;
343 if (GEP1->getPointerOperand()->getType() !=
344 GEP2->getPointerOperand()->getType())
347 if (GEP1->getNumOperands() != GEP2->getNumOperands())
350 for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
351 if (!Enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
358 /// getDomain - a value's domain is its parent function if it is specific to a
359 /// function, or NULL otherwise.
360 const Function *FunctionComparator::getDomain(const Value *V) const {
361 if (const Argument *A = dyn_cast<Argument>(V)) {
362 return A->getParent();
363 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
364 return BB->getParent();
365 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
366 return I->getParent()->getParent();
371 /// Enumerate - Compare two values used by the two functions under pair-wise
372 /// comparison. If this is the first time the values are seen, they're added to
373 /// the mapping so that we will detect mismatches on next use.
374 bool FunctionComparator::Enumerate(const Value *V1, const Value *V2) {
375 // Check for function @f1 referring to itself and function @f2 referring to
376 // itself, or referring to each other, or both referring to either of them.
377 // They're all equivalent if the two functions are otherwise equivalent.
378 if (V1 == F1 || V1 == F2)
379 if (V2 == F1 || V2 == F2)
382 // TODO: constant expressions with GEP or references to F1 or F2.
383 if (isa<Constant>(V1))
386 if (isa<InlineAsm>(V1) && isa<InlineAsm>(V2)) {
387 const InlineAsm *IA1 = cast<InlineAsm>(V1);
388 const InlineAsm *IA2 = cast<InlineAsm>(V2);
389 return IA1->getAsmString() == IA2->getAsmString() &&
390 IA1->getConstraintString() == IA2->getConstraintString();
393 // We enumerate constants globally and arguments, basic blocks or
394 // instructions within the function they belong to.
395 const Function *Domain1 = getDomain(V1);
396 const Function *Domain2 = getDomain(V2);
398 // The domains have to either be both NULL, or F1, F2.
399 if (Domain1 != Domain2)
400 if (Domain1 != F1 && Domain1 != F2)
403 IDMap &Map1 = Domains[Domain1];
404 unsigned long &ID1 = Map1[V1];
406 ID1 = ++DomainCount[Domain1];
408 IDMap &Map2 = Domains[Domain2];
409 unsigned long &ID2 = Map2[V2];
411 ID2 = ++DomainCount[Domain2];
416 // Compare - test whether two basic blocks have equivalent behaviour.
417 bool FunctionComparator::Compare(const BasicBlock *BB1, const BasicBlock *BB2) {
418 BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
419 BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
422 if (!Enumerate(F1I, F2I))
425 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
426 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
430 if (!Enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
433 if (!isEquivalentGEP(GEP1, GEP2))
436 if (!isEquivalentOperation(F1I, F2I))
439 assert(F1I->getNumOperands() == F2I->getNumOperands());
440 for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
441 Value *OpF1 = F1I->getOperand(i);
442 Value *OpF2 = F2I->getOperand(i);
444 if (!Enumerate(OpF1, OpF2))
447 if (OpF1->getValueID() != OpF2->getValueID() ||
448 !isEquivalentType(OpF1->getType(), OpF2->getType()))
454 } while (F1I != F1E && F2I != F2E);
456 return F1I == F1E && F2I == F2E;
459 bool FunctionComparator::Compare() {
460 // We need to recheck everything, but check the things that weren't included
461 // in the hash first.
463 if (F1->getAttributes() != F2->getAttributes())
466 if (F1->hasGC() != F2->hasGC())
469 if (F1->hasGC() && F1->getGC() != F2->getGC())
472 if (F1->hasSection() != F2->hasSection())
475 if (F1->hasSection() && F1->getSection() != F2->getSection())
478 if (F1->isVarArg() != F2->isVarArg())
481 // TODO: if it's internal and only used in direct calls, we could handle this
483 if (F1->getCallingConv() != F2->getCallingConv())
486 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
489 assert(F1->arg_size() == F2->arg_size() &&
490 "Identical functions have a different number of args.");
492 // Visit the arguments so that they get enumerated in the order they're
494 for (Function::const_arg_iterator f1i = F1->arg_begin(),
495 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
496 if (!Enumerate(f1i, f2i))
497 llvm_unreachable("Arguments repeat");
500 // We need to do an ordered walk since the actual ordering of the blocks in
501 // the linked list is immaterial. Our walk starts at the entry block for both
502 // functions, then takes each block from each terminator in order. As an
503 // artifact, this also means that unreachable blocks are ignored.
504 SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
505 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
506 F1BBs.push_back(&F1->getEntryBlock());
507 F2BBs.push_back(&F2->getEntryBlock());
508 VisitedBBs.insert(F1BBs[0]);
509 while (!F1BBs.empty()) {
510 const BasicBlock *F1BB = F1BBs.pop_back_val();
511 const BasicBlock *F2BB = F2BBs.pop_back_val();
512 if (!Enumerate(F1BB, F2BB) || !Compare(F1BB, F2BB))
514 const TerminatorInst *F1TI = F1BB->getTerminator();
515 const TerminatorInst *F2TI = F2BB->getTerminator();
516 assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
517 for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
518 if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
520 F1BBs.push_back(F1TI->getSuccessor(i));
521 F2BBs.push_back(F2TI->getSuccessor(i));
527 // ===----------------------------------------------------------------------===
528 // Folding of functions
529 // ===----------------------------------------------------------------------===
532 // * F is external strong, G is external strong:
533 // turn G into a thunk to F (1)
534 // * F is external strong, G is external weak:
535 // turn G into a thunk to F (1)
536 // * F is external weak, G is external weak:
538 // * F is external strong, G is internal:
539 // address of G taken:
540 // turn G into a thunk to F (1)
541 // address of G not taken:
542 // make G an alias to F (2)
543 // * F is internal, G is external weak
544 // address of F is taken:
545 // turn G into a thunk to F (1)
546 // address of F is not taken:
547 // make G an alias of F (2)
548 // * F is internal, G is internal:
549 // address of F and G are taken:
550 // turn G into a thunk to F (1)
551 // address of G is not taken:
552 // make G an alias to F (2)
554 // alias requires linkage == (external,local,weak) fallback to creating a thunk
555 // external means 'externally visible' linkage != (internal,private)
556 // internal means linkage == (internal,private)
557 // weak means linkage mayBeOverridable
558 // being external implies that the address is taken
560 // 1. turn G into a thunk to F
561 // 2. make G an alias to F
563 enum LinkageCategory {
569 static LinkageCategory categorize(const Function *F) {
570 switch (F->getLinkage()) {
571 case GlobalValue::InternalLinkage:
572 case GlobalValue::PrivateLinkage:
573 case GlobalValue::LinkerPrivateLinkage:
576 case GlobalValue::WeakAnyLinkage:
577 case GlobalValue::WeakODRLinkage:
578 case GlobalValue::ExternalWeakLinkage:
579 case GlobalValue::LinkerPrivateWeakLinkage:
582 case GlobalValue::ExternalLinkage:
583 case GlobalValue::AvailableExternallyLinkage:
584 case GlobalValue::LinkOnceAnyLinkage:
585 case GlobalValue::LinkOnceODRLinkage:
586 case GlobalValue::AppendingLinkage:
587 case GlobalValue::DLLImportLinkage:
588 case GlobalValue::DLLExportLinkage:
589 case GlobalValue::CommonLinkage:
590 return ExternalStrong;
593 llvm_unreachable("Unknown LinkageType.");
597 static void ThunkGToF(Function *F, Function *G) {
598 if (!G->mayBeOverridden()) {
599 // Redirect direct callers of G to F.
600 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
601 for (Value::use_iterator UI = G->use_begin(), UE = G->use_end();
603 Value::use_iterator TheIter = UI;
605 CallSite CS(*TheIter);
606 if (CS && CS.isCallee(TheIter))
607 TheIter.getUse().set(BitcastF);
611 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
613 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
615 SmallVector<Value *, 16> Args;
617 const FunctionType *FFTy = F->getFunctionType();
618 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
620 if (FFTy->getParamType(i) == AI->getType()) {
623 Args.push_back(new BitCastInst(AI, FFTy->getParamType(i), "", BB));
628 CallInst *CI = CallInst::Create(F, Args.begin(), Args.end(), "", BB);
630 CI->setCallingConv(F->getCallingConv());
631 if (NewG->getReturnType()->isVoidTy()) {
632 ReturnInst::Create(F->getContext(), BB);
633 } else if (CI->getType() != NewG->getReturnType()) {
634 Value *BCI = new BitCastInst(CI, NewG->getReturnType(), "", BB);
635 ReturnInst::Create(F->getContext(), BCI, BB);
637 ReturnInst::Create(F->getContext(), CI, BB);
640 NewG->copyAttributesFrom(G);
642 G->replaceAllUsesWith(NewG);
643 G->eraseFromParent();
646 static void AliasGToF(Function *F, Function *G) {
647 // Darwin will trigger llvm_unreachable if asked to codegen an alias.
648 return ThunkGToF(F, G);
651 if (!G->hasExternalLinkage() && !G->hasLocalLinkage() && !G->hasWeakLinkage())
652 return ThunkGToF(F, G);
654 GlobalAlias *GA = new GlobalAlias(
655 G->getType(), G->getLinkage(), "",
656 ConstantExpr::getBitCast(F, G->getType()), G->getParent());
657 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
659 GA->setVisibility(G->getVisibility());
660 G->replaceAllUsesWith(GA);
661 G->eraseFromParent();
665 static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) {
666 Function *F = FnVec[i];
667 Function *G = FnVec[j];
669 LinkageCategory catF = categorize(F);
670 LinkageCategory catG = categorize(G);
672 if (catF == ExternalWeak || (catF == Internal && catG == ExternalStrong)) {
673 std::swap(FnVec[i], FnVec[j]);
675 std::swap(catF, catG);
686 if (G->hasAddressTaken())
695 assert(catG == ExternalWeak);
697 // Make them both thunks to the same internal function.
698 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
699 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
701 H->copyAttributesFrom(F);
703 F->replaceAllUsesWith(H);
708 F->setLinkage(GlobalValue::InternalLinkage);
717 if (F->hasAddressTaken())
723 bool addrTakenF = F->hasAddressTaken();
724 bool addrTakenG = G->hasAddressTaken();
725 if (!addrTakenF && addrTakenG) {
726 std::swap(FnVec[i], FnVec[j]);
728 std::swap(addrTakenF, addrTakenG);
731 if (addrTakenF && addrTakenG) {
741 ++NumFunctionsMerged;
745 // ===----------------------------------------------------------------------===
747 // ===----------------------------------------------------------------------===
749 bool MergeFunctions::runOnModule(Module &M) {
750 bool Changed = false;
752 std::map<unsigned long, std::vector<Function *> > FnMap;
754 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
755 if (F->isDeclaration())
758 FnMap[ProfileFunction(F)].push_back(F);
761 TargetData *TD = getAnalysisIfAvailable<TargetData>();
765 LocalChanged = false;
766 DEBUG(dbgs() << "size: " << FnMap.size() << "\n");
767 for (std::map<unsigned long, std::vector<Function *> >::iterator
768 I = FnMap.begin(), E = FnMap.end(); I != E; ++I) {
769 std::vector<Function *> &FnVec = I->second;
770 DEBUG(dbgs() << "hash (" << I->first << "): " << FnVec.size() << "\n");
772 for (int i = 0, e = FnVec.size(); i != e; ++i) {
773 for (int j = i + 1; j != e; ++j) {
774 bool isEqual = FunctionComparator(TD, FnVec[i], FnVec[j]).Compare();
776 DEBUG(dbgs() << " " << FnVec[i]->getName()
777 << (isEqual ? " == " : " != ")
778 << FnVec[j]->getName() << "\n");
781 if (fold(FnVec, i, j)) {
783 FnVec.erase(FnVec.begin() + j);
791 Changed |= LocalChanged;
792 } while (LocalChanged);