blob: 3b5446257443efd24ba73a6fee2b8a78664bb929 [file] [log] [blame]
Nick Lewycky579a0242008-11-02 05:52:50 +00001//===- 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//
Nick Lewycky579a0242008-11-02 05:52:50 +000012// 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.
Nick Lewycky579a0242008-11-02 05:52:50 +000023//
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"
Nick Lewycky287de602009-06-12 08:04:51 +000045#include "llvm/ADT/FoldingSet.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000046#include "llvm/ADT/Statistic.h"
47#include "llvm/Constants.h"
48#include "llvm/InlineAsm.h"
49#include "llvm/Instructions.h"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000050#include "llvm/LLVMContext.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000051#include "llvm/Module.h"
52#include "llvm/Pass.h"
Nick Lewycky6feb3332008-11-02 16:46:26 +000053#include "llvm/Support/CallSite.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000054#include "llvm/Support/Compiler.h"
55#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000056#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000057#include "llvm/Support/raw_ostream.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000058#include <map>
59#include <vector>
60using namespace llvm;
61
62STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky579a0242008-11-02 05:52:50 +000063
64namespace {
65 struct VISIBILITY_HIDDEN MergeFunctions : public ModulePass {
66 static char ID; // Pass identification, replacement for typeid
67 MergeFunctions() : ModulePass((intptr_t)&ID) {}
68
69 bool runOnModule(Module &M);
70 };
71}
72
73char MergeFunctions::ID = 0;
74static RegisterPass<MergeFunctions>
75X("mergefunc", "Merge Functions");
76
77ModulePass *llvm::createMergeFunctionsPass() {
78 return new MergeFunctions();
79}
80
Nick Lewycky287de602009-06-12 08:04:51 +000081// ===----------------------------------------------------------------------===
82// Comparison of functions
83// ===----------------------------------------------------------------------===
84
Duncan Sands5baf8ec2008-11-02 09:00:33 +000085static unsigned long hash(const Function *F) {
Nick Lewycky287de602009-06-12 08:04:51 +000086 const FunctionType *FTy = F->getFunctionType();
87
88 FoldingSetNodeID ID;
89 ID.AddInteger(F->size());
90 ID.AddInteger(F->getCallingConv());
91 ID.AddBoolean(F->hasGC());
92 ID.AddBoolean(FTy->isVarArg());
93 ID.AddInteger(FTy->getReturnType()->getTypeID());
94 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
95 ID.AddInteger(FTy->getParamType(i)->getTypeID());
96 return ID.ComputeHash();
97}
98
99/// IgnoreBitcasts - given a bitcast, returns the first non-bitcast found by
100/// walking the chain of cast operands. Otherwise, returns the argument.
101static Value* IgnoreBitcasts(Value *V) {
102 while (BitCastInst *BC = dyn_cast<BitCastInst>(V))
103 V = BC->getOperand(0);
104
105 return V;
106}
107
108/// isEquivalentType - any two pointers are equivalent. Otherwise, standard
109/// type equivalence rules apply.
110static bool isEquivalentType(const Type *Ty1, const Type *Ty2) {
111 if (Ty1 == Ty2)
112 return true;
113 if (Ty1->getTypeID() != Ty2->getTypeID())
114 return false;
115
116 switch(Ty1->getTypeID()) {
117 case Type::VoidTyID:
118 case Type::FloatTyID:
119 case Type::DoubleTyID:
120 case Type::X86_FP80TyID:
121 case Type::FP128TyID:
122 case Type::PPC_FP128TyID:
123 case Type::LabelTyID:
124 case Type::MetadataTyID:
125 return true;
126
127 case Type::IntegerTyID:
128 case Type::OpaqueTyID:
129 // Ty1 == Ty2 would have returned true earlier.
130 return false;
131
132 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000133 llvm_unreachable("Unknown type!");
Nick Lewycky287de602009-06-12 08:04:51 +0000134 return false;
135
136 case Type::PointerTyID: {
137 const PointerType *PTy1 = cast<PointerType>(Ty1);
138 const PointerType *PTy2 = cast<PointerType>(Ty2);
139 return PTy1->getAddressSpace() == PTy2->getAddressSpace();
140 }
141
142 case Type::StructTyID: {
143 const StructType *STy1 = cast<StructType>(Ty1);
144 const StructType *STy2 = cast<StructType>(Ty2);
145 if (STy1->getNumElements() != STy2->getNumElements())
146 return false;
147
148 if (STy1->isPacked() != STy2->isPacked())
149 return false;
150
151 for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) {
152 if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i)))
153 return false;
154 }
155 return true;
156 }
157
158 case Type::FunctionTyID: {
159 const FunctionType *FTy1 = cast<FunctionType>(Ty1);
160 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
161 if (FTy1->getNumParams() != FTy2->getNumParams() ||
162 FTy1->isVarArg() != FTy2->isVarArg())
163 return false;
164
165 if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType()))
166 return false;
167
168 for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) {
169 if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i)))
170 return false;
171 }
172 return true;
173 }
174
175 case Type::ArrayTyID:
176 case Type::VectorTyID: {
177 const SequentialType *STy1 = cast<SequentialType>(Ty1);
178 const SequentialType *STy2 = cast<SequentialType>(Ty2);
179 return isEquivalentType(STy1->getElementType(), STy2->getElementType());
180 }
181 }
182}
183
184/// isEquivalentOperation - determine whether the two operations are the same
185/// except that pointer-to-A and pointer-to-B are equivalent. This should be
Dan Gohman194ae782009-06-12 19:03:05 +0000186/// kept in sync with Instruction::isSameOperationAs.
187static bool
188isEquivalentOperation(const Instruction *I1, const Instruction *I2) {
Nick Lewycky287de602009-06-12 08:04:51 +0000189 if (I1->getOpcode() != I2->getOpcode() ||
190 I1->getNumOperands() != I2->getNumOperands() ||
191 !isEquivalentType(I1->getType(), I2->getType()))
192 return false;
193
194 // We have two instructions of identical opcode and #operands. Check to see
195 // if all operands are the same type
196 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
197 if (!isEquivalentType(I1->getOperand(i)->getType(),
198 I2->getOperand(i)->getType()))
199 return false;
200
201 // Check special state that is a part of some instructions.
202 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
203 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
204 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment();
205 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
206 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
207 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment();
208 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
209 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
210 if (const CallInst *CI = dyn_cast<CallInst>(I1))
211 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
212 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
213 CI->getAttributes().getRawPointer() ==
214 cast<CallInst>(I2)->getAttributes().getRawPointer();
215 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
216 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
217 CI->getAttributes().getRawPointer() ==
218 cast<InvokeInst>(I2)->getAttributes().getRawPointer();
219 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) {
220 if (IVI->getNumIndices() != cast<InsertValueInst>(I2)->getNumIndices())
221 return false;
222 for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i)
223 if (IVI->idx_begin()[i] != cast<InsertValueInst>(I2)->idx_begin()[i])
224 return false;
225 return true;
226 }
227 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) {
228 if (EVI->getNumIndices() != cast<ExtractValueInst>(I2)->getNumIndices())
229 return false;
230 for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i)
231 if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I2)->idx_begin()[i])
232 return false;
233 return true;
234 }
235
236 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000237}
238
239static bool compare(const Value *V, const Value *U) {
240 assert(!isa<BasicBlock>(V) && !isa<BasicBlock>(U) &&
241 "Must not compare basic blocks.");
242
Nick Lewycky287de602009-06-12 08:04:51 +0000243 assert(isEquivalentType(V->getType(), U->getType()) &&
Nick Lewycky579a0242008-11-02 05:52:50 +0000244 "Two of the same operation have operands of different type.");
245
246 // TODO: If the constant is an expression of F, we should accept that it's
247 // equal to the same expression in terms of G.
248 if (isa<Constant>(V))
249 return V == U;
250
251 // The caller has ensured that ValueMap[V] != U. Since Arguments are
252 // pre-loaded into the ValueMap, and Instructions are added as we go, we know
253 // that this can only be a mis-match.
254 if (isa<Instruction>(V) || isa<Argument>(V))
255 return false;
256
257 if (isa<InlineAsm>(V) && isa<InlineAsm>(U)) {
258 const InlineAsm *IAF = cast<InlineAsm>(V);
259 const InlineAsm *IAG = cast<InlineAsm>(U);
260 return IAF->getAsmString() == IAG->getAsmString() &&
261 IAF->getConstraintString() == IAG->getConstraintString();
262 }
263
264 return false;
265}
266
267static bool equals(const BasicBlock *BB1, const BasicBlock *BB2,
268 DenseMap<const Value *, const Value *> &ValueMap,
269 DenseMap<const Value *, const Value *> &SpeculationMap) {
Nick Lewycky287de602009-06-12 08:04:51 +0000270 // Speculatively add it anyways. If it's false, we'll notice a difference
271 // later, and this won't matter.
Nick Lewycky579a0242008-11-02 05:52:50 +0000272 ValueMap[BB1] = BB2;
273
274 BasicBlock::const_iterator FI = BB1->begin(), FE = BB1->end();
275 BasicBlock::const_iterator GI = BB2->begin(), GE = BB2->end();
276
277 do {
Nick Lewycky287de602009-06-12 08:04:51 +0000278 if (isa<BitCastInst>(FI)) {
279 ++FI;
280 continue;
281 }
282 if (isa<BitCastInst>(GI)) {
283 ++GI;
284 continue;
285 }
Nick Lewycky579a0242008-11-02 05:52:50 +0000286
Nick Lewycky287de602009-06-12 08:04:51 +0000287 if (!isEquivalentOperation(FI, GI))
Nick Lewycky579a0242008-11-02 05:52:50 +0000288 return false;
289
Nick Lewyckya142c932009-06-13 19:09:52 +0000290 if (isa<GetElementPtrInst>(FI)) {
291 const GetElementPtrInst *GEPF = cast<GetElementPtrInst>(FI);
292 const GetElementPtrInst *GEPG = cast<GetElementPtrInst>(GI);
293 if (GEPF->hasAllZeroIndices() && GEPG->hasAllZeroIndices()) {
294 // It's effectively a bitcast.
295 ++FI, ++GI;
296 continue;
297 }
298
299 // TODO: we only really care about the elements before the index
300 if (FI->getOperand(0)->getType() != GI->getOperand(0)->getType())
301 return false;
302 }
303
Nick Lewycky579a0242008-11-02 05:52:50 +0000304 if (ValueMap[FI] == GI) {
305 ++FI, ++GI;
306 continue;
307 }
308
309 if (ValueMap[FI] != NULL)
310 return false;
311
312 for (unsigned i = 0, e = FI->getNumOperands(); i != e; ++i) {
Nick Lewycky287de602009-06-12 08:04:51 +0000313 Value *OpF = IgnoreBitcasts(FI->getOperand(i));
314 Value *OpG = IgnoreBitcasts(GI->getOperand(i));
Nick Lewycky579a0242008-11-02 05:52:50 +0000315
316 if (ValueMap[OpF] == OpG)
317 continue;
318
319 if (ValueMap[OpF] != NULL)
320 return false;
321
Nick Lewycky287de602009-06-12 08:04:51 +0000322 if (OpF->getValueID() != OpG->getValueID() ||
323 !isEquivalentType(OpF->getType(), OpG->getType()))
Nick Lewycky579a0242008-11-02 05:52:50 +0000324 return false;
325
326 if (isa<PHINode>(FI)) {
327 if (SpeculationMap[OpF] == NULL)
328 SpeculationMap[OpF] = OpG;
329 else if (SpeculationMap[OpF] != OpG)
330 return false;
331 continue;
332 } else if (isa<BasicBlock>(OpF)) {
333 assert(isa<TerminatorInst>(FI) &&
334 "BasicBlock referenced by non-Terminator non-PHI");
335 // This call changes the ValueMap, hence we can't use
336 // Value *& = ValueMap[...]
337 if (!equals(cast<BasicBlock>(OpF), cast<BasicBlock>(OpG), ValueMap,
338 SpeculationMap))
339 return false;
340 } else {
341 if (!compare(OpF, OpG))
342 return false;
343 }
344
345 ValueMap[OpF] = OpG;
346 }
347
348 ValueMap[FI] = GI;
349 ++FI, ++GI;
350 } while (FI != FE && GI != GE);
351
352 return FI == FE && GI == GE;
353}
354
355static bool equals(const Function *F, const Function *G) {
356 // We need to recheck everything, but check the things that weren't included
357 // in the hash first.
358
359 if (F->getAttributes() != G->getAttributes())
360 return false;
361
362 if (F->hasGC() != G->hasGC())
363 return false;
364
365 if (F->hasGC() && F->getGC() != G->getGC())
366 return false;
367
368 if (F->hasSection() != G->hasSection())
369 return false;
370
371 if (F->hasSection() && F->getSection() != G->getSection())
372 return false;
373
Nick Lewycky287de602009-06-12 08:04:51 +0000374 if (F->isVarArg() != G->isVarArg())
375 return false;
376
Nick Lewycky579a0242008-11-02 05:52:50 +0000377 // TODO: if it's internal and only used in direct calls, we could handle this
378 // case too.
379 if (F->getCallingConv() != G->getCallingConv())
380 return false;
381
Nick Lewycky287de602009-06-12 08:04:51 +0000382 if (!isEquivalentType(F->getFunctionType(), G->getFunctionType()))
Nick Lewycky579a0242008-11-02 05:52:50 +0000383 return false;
384
385 DenseMap<const Value *, const Value *> ValueMap;
386 DenseMap<const Value *, const Value *> SpeculationMap;
387 ValueMap[F] = G;
388
389 assert(F->arg_size() == G->arg_size() &&
390 "Identical functions have a different number of args.");
391
392 for (Function::const_arg_iterator fi = F->arg_begin(), gi = G->arg_begin(),
393 fe = F->arg_end(); fi != fe; ++fi, ++gi)
394 ValueMap[fi] = gi;
395
396 if (!equals(&F->getEntryBlock(), &G->getEntryBlock(), ValueMap,
397 SpeculationMap))
398 return false;
399
400 for (DenseMap<const Value *, const Value *>::iterator
401 I = SpeculationMap.begin(), E = SpeculationMap.end(); I != E; ++I) {
402 if (ValueMap[I->first] != I->second)
403 return false;
404 }
405
406 return true;
407}
408
Nick Lewycky287de602009-06-12 08:04:51 +0000409// ===----------------------------------------------------------------------===
410// Folding of functions
411// ===----------------------------------------------------------------------===
Nick Lewycky579a0242008-11-02 05:52:50 +0000412
Nick Lewycky287de602009-06-12 08:04:51 +0000413// Cases:
414// * F is external strong, G is external strong:
415// turn G into a thunk to F (1)
416// * F is external strong, G is external weak:
417// turn G into a thunk to F (1)
418// * F is external weak, G is external weak:
419// unfoldable
420// * F is external strong, G is internal:
421// address of G taken:
422// turn G into a thunk to F (1)
423// address of G not taken:
424// make G an alias to F (2)
425// * F is internal, G is external weak
426// address of F is taken:
427// turn G into a thunk to F (1)
428// address of F is not taken:
429// make G an alias of F (2)
430// * F is internal, G is internal:
431// address of F and G are taken:
432// turn G into a thunk to F (1)
433// address of G is not taken:
434// make G an alias to F (2)
435//
436// alias requires linkage == (external,local,weak) fallback to creating a thunk
437// external means 'externally visible' linkage != (internal,private)
438// internal means linkage == (internal,private)
439// weak means linkage mayBeOverridable
440// being external implies that the address is taken
441//
442// 1. turn G into a thunk to F
443// 2. make G an alias to F
444
445enum LinkageCategory {
446 ExternalStrong,
447 ExternalWeak,
448 Internal
449};
450
451static LinkageCategory categorize(const Function *F) {
452 switch (F->getLinkage()) {
453 case GlobalValue::InternalLinkage:
454 case GlobalValue::PrivateLinkage:
Bill Wendling3d10a5a2009-07-20 01:03:30 +0000455 case GlobalValue::LinkerPrivateLinkage:
Nick Lewycky287de602009-06-12 08:04:51 +0000456 return Internal;
457
458 case GlobalValue::WeakAnyLinkage:
459 case GlobalValue::WeakODRLinkage:
460 case GlobalValue::ExternalWeakLinkage:
461 return ExternalWeak;
462
463 case GlobalValue::ExternalLinkage:
464 case GlobalValue::AvailableExternallyLinkage:
465 case GlobalValue::LinkOnceAnyLinkage:
466 case GlobalValue::LinkOnceODRLinkage:
467 case GlobalValue::AppendingLinkage:
468 case GlobalValue::DLLImportLinkage:
469 case GlobalValue::DLLExportLinkage:
470 case GlobalValue::GhostLinkage:
471 case GlobalValue::CommonLinkage:
472 return ExternalStrong;
473 }
474
Torok Edwinc23197a2009-07-14 16:55:14 +0000475 llvm_unreachable("Unknown LinkageType.");
Nick Lewycky287de602009-06-12 08:04:51 +0000476 return ExternalWeak;
477}
478
479static void ThunkGToF(Function *F, Function *G) {
Nick Lewycky8728d7a2009-06-12 15:56:56 +0000480 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
481 G->getParent());
Nick Lewycky287de602009-06-12 08:04:51 +0000482 BasicBlock *BB = BasicBlock::Create("", NewG);
483
484 std::vector<Value *> Args;
485 unsigned i = 0;
486 const FunctionType *FFTy = F->getFunctionType();
487 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
488 AI != AE; ++AI) {
489 if (FFTy->getParamType(i) == AI->getType())
490 Args.push_back(AI);
491 else {
492 Value *BCI = new BitCastInst(AI, FFTy->getParamType(i), "", BB);
493 Args.push_back(BCI);
494 }
495 ++i;
496 }
497
498 CallInst *CI = CallInst::Create(F, Args.begin(), Args.end(), "", BB);
499 CI->setTailCall();
Nick Lewyckyb3c36c92009-06-12 16:04:00 +0000500 CI->setCallingConv(F->getCallingConv());
Nick Lewycky287de602009-06-12 08:04:51 +0000501 if (NewG->getReturnType() == Type::VoidTy) {
502 ReturnInst::Create(BB);
503 } else if (CI->getType() != NewG->getReturnType()) {
504 Value *BCI = new BitCastInst(CI, NewG->getReturnType(), "", BB);
505 ReturnInst::Create(BCI, BB);
506 } else {
507 ReturnInst::Create(CI, BB);
508 }
509
510 NewG->copyAttributesFrom(G);
511 NewG->takeName(G);
512 G->replaceAllUsesWith(NewG);
513 G->eraseFromParent();
514
Nick Lewyckyb3c36c92009-06-12 16:04:00 +0000515 // TODO: look at direct callers to G and make them all direct callers to F.
Nick Lewycky287de602009-06-12 08:04:51 +0000516}
517
518static void AliasGToF(Function *F, Function *G) {
519 if (!G->hasExternalLinkage() && !G->hasLocalLinkage() && !G->hasWeakLinkage())
520 return ThunkGToF(F, G);
521
522 GlobalAlias *GA = new GlobalAlias(
523 G->getType(), G->getLinkage(), "",
Owen Andersone922c022009-07-22 00:24:57 +0000524 F->getContext().getConstantExprBitCast(F, G->getType()), G->getParent());
Nick Lewycky287de602009-06-12 08:04:51 +0000525 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
526 GA->takeName(G);
527 GA->setVisibility(G->getVisibility());
528 G->replaceAllUsesWith(GA);
529 G->eraseFromParent();
530}
531
532static bool fold(std::vector<Function *> &FnVec, unsigned i, unsigned j) {
Nick Lewycky579a0242008-11-02 05:52:50 +0000533 Function *F = FnVec[i];
534 Function *G = FnVec[j];
535
Nick Lewycky287de602009-06-12 08:04:51 +0000536 LinkageCategory catF = categorize(F);
537 LinkageCategory catG = categorize(G);
Nick Lewycky579a0242008-11-02 05:52:50 +0000538
Nick Lewycky287de602009-06-12 08:04:51 +0000539 if (catF == ExternalWeak || (catF == Internal && catG == ExternalStrong)) {
540 std::swap(FnVec[i], FnVec[j]);
541 std::swap(F, G);
542 std::swap(catF, catG);
Nick Lewycky579a0242008-11-02 05:52:50 +0000543 }
544
Nick Lewycky287de602009-06-12 08:04:51 +0000545 switch (catF) {
546 case ExternalStrong:
547 switch (catG) {
548 case ExternalStrong:
549 case ExternalWeak:
550 ThunkGToF(F, G);
551 break;
552 case Internal:
553 if (G->hasAddressTaken())
554 ThunkGToF(F, G);
555 else
556 AliasGToF(F, G);
557 break;
558 }
559 break;
Nick Lewycky6feb3332008-11-02 16:46:26 +0000560
Nick Lewycky8728d7a2009-06-12 15:56:56 +0000561 case ExternalWeak: {
562 assert(catG == ExternalWeak);
563
564 // Make them both thunks to the same internal function.
565 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
566 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
567 F->getParent());
568 H->copyAttributesFrom(F);
569 H->takeName(F);
Nick Lewycky93531e42009-06-12 17:16:48 +0000570 F->replaceAllUsesWith(H);
Nick Lewycky8728d7a2009-06-12 15:56:56 +0000571
572 ThunkGToF(F, G);
573 ThunkGToF(F, H);
574
575 F->setLinkage(GlobalValue::InternalLinkage);
576 } break;
Nick Lewycky6feb3332008-11-02 16:46:26 +0000577
Nick Lewycky287de602009-06-12 08:04:51 +0000578 case Internal:
579 switch (catG) {
580 case ExternalStrong:
Torok Edwinc23197a2009-07-14 16:55:14 +0000581 llvm_unreachable(0);
Nick Lewycky287de602009-06-12 08:04:51 +0000582 // fall-through
583 case ExternalWeak:
584 if (F->hasAddressTaken())
585 ThunkGToF(F, G);
586 else
587 AliasGToF(F, G);
588 break;
589 case Internal: {
590 bool addrTakenF = F->hasAddressTaken();
591 bool addrTakenG = G->hasAddressTaken();
592 if (!addrTakenF && addrTakenG) {
593 std::swap(FnVec[i], FnVec[j]);
594 std::swap(F, G);
595 std::swap(addrTakenF, addrTakenG);
596 }
597
598 if (addrTakenF && addrTakenG) {
599 ThunkGToF(F, G);
600 } else {
601 assert(!addrTakenG);
602 AliasGToF(F, G);
603 }
604 } break;
605 }
606 break;
Nick Lewycky6feb3332008-11-02 16:46:26 +0000607 }
608
Nick Lewycky287de602009-06-12 08:04:51 +0000609 ++NumFunctionsMerged;
610 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000611}
612
Nick Lewycky287de602009-06-12 08:04:51 +0000613// ===----------------------------------------------------------------------===
614// Pass definition
615// ===----------------------------------------------------------------------===
Nick Lewycky579a0242008-11-02 05:52:50 +0000616
617bool MergeFunctions::runOnModule(Module &M) {
618 bool Changed = false;
619
Duncan Sands5baf8ec2008-11-02 09:00:33 +0000620 std::map<unsigned long, std::vector<Function *> > FnMap;
Nick Lewycky579a0242008-11-02 05:52:50 +0000621
622 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
623 if (F->isDeclaration() || F->isIntrinsic())
624 continue;
625
Nick Lewycky579a0242008-11-02 05:52:50 +0000626 FnMap[hash(F)].push_back(F);
627 }
628
Nick Lewycky287de602009-06-12 08:04:51 +0000629 // TODO: instead of running in a loop, we could also fold functions in
630 // callgraph order. Constructing the CFG probably isn't cheaper than just
631 // running in a loop, unless it happened to already be available.
Nick Lewycky579a0242008-11-02 05:52:50 +0000632
633 bool LocalChanged;
634 do {
635 LocalChanged = false;
Nick Lewycky287de602009-06-12 08:04:51 +0000636 DOUT << "size: " << FnMap.size() << "\n";
Duncan Sands5baf8ec2008-11-02 09:00:33 +0000637 for (std::map<unsigned long, std::vector<Function *> >::iterator
638 I = FnMap.begin(), E = FnMap.end(); I != E; ++I) {
Nick Lewycky579a0242008-11-02 05:52:50 +0000639 std::vector<Function *> &FnVec = I->second;
640 DOUT << "hash (" << I->first << "): " << FnVec.size() << "\n";
641
642 for (int i = 0, e = FnVec.size(); i != e; ++i) {
643 for (int j = i + 1; j != e; ++j) {
644 bool isEqual = equals(FnVec[i], FnVec[j]);
645
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000646 DEBUG(errs() << " " << FnVec[i]->getName()
647 << (isEqual ? " == " : " != ")
648 << FnVec[j]->getName() << "\n");
Nick Lewycky579a0242008-11-02 05:52:50 +0000649
650 if (isEqual) {
651 if (fold(FnVec, i, j)) {
652 LocalChanged = true;
653 FnVec.erase(FnVec.begin() + j);
654 --j, --e;
655 }
656 }
657 }
658 }
659
660 }
661 Changed |= LocalChanged;
662 } while (LocalChanged);
663
664 return Changed;
665}