blob: cefed1a059af78c27bc2bad3084b38c019023c21 [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//
Nick Lewycky33ab0b12010-05-13 05:48:45 +000020// 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.
Nick Lewycky579a0242008-11-02 05:52:50 +000023//
24//===----------------------------------------------------------------------===//
25//
26// Future work:
27//
Nick Lewycky579a0242008-11-02 05:52:50 +000028// * virtual functions.
29//
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
Nick Lewyckybe04fde2010-08-08 05:04:23 +000032// and call, this is irrelevant, and we'd like to fold such functions.
Nick Lewycky579a0242008-11-02 05:52:50 +000033//
Nick Lewycky78d43302010-08-02 05:23:03 +000034// * switch from n^2 pair-wise comparisons to an n-way comparison for each
35// bucket.
Nick Lewycky33ab0b12010-05-13 05:48:45 +000036//
Nick Lewyckybe04fde2010-08-08 05:04:23 +000037// * be smarter about bitcasts.
Nick Lewycky33ab0b12010-05-13 05:48:45 +000038//
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
Nick Lewyckybe04fde2010-08-08 05:04:23 +000042// other doesn't. We should learn to look through bitcasts.
Nick Lewycky33ab0b12010-05-13 05:48:45 +000043//
Nick Lewycky579a0242008-11-02 05:52:50 +000044//===----------------------------------------------------------------------===//
45
46#define DEBUG_TYPE "mergefunc"
47#include "llvm/Transforms/IPO.h"
Nick Lewyckyf53de862010-08-31 05:53:05 +000048#include "llvm/ADT/DenseSet.h"
Nick Lewycky287de602009-06-12 08:04:51 +000049#include "llvm/ADT/FoldingSet.h"
Nick Lewycky33ab0b12010-05-13 05:48:45 +000050#include "llvm/ADT/SmallSet.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000051#include "llvm/ADT/Statistic.h"
Nick Lewyckyf53de862010-08-31 05:53:05 +000052#include "llvm/ADT/STLExtras.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000053#include "llvm/Constants.h"
54#include "llvm/InlineAsm.h"
55#include "llvm/Instructions.h"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000056#include "llvm/LLVMContext.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000057#include "llvm/Module.h"
58#include "llvm/Pass.h"
Nick Lewycky6feb3332008-11-02 16:46:26 +000059#include "llvm/Support/CallSite.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000060#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000061#include "llvm/Support/ErrorHandling.h"
Nick Lewyckybe04fde2010-08-08 05:04:23 +000062#include "llvm/Support/IRBuilder.h"
Nick Lewyckyf53de862010-08-31 05:53:05 +000063#include "llvm/Support/ValueHandle.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000064#include "llvm/Support/raw_ostream.h"
Nick Lewycky33ab0b12010-05-13 05:48:45 +000065#include "llvm/Target/TargetData.h"
Nick Lewycky579a0242008-11-02 05:52:50 +000066using namespace llvm;
67
68STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky579a0242008-11-02 05:52:50 +000069
70namespace {
Nick Lewycky78d43302010-08-02 05:23:03 +000071 /// MergeFunctions finds functions which will generate identical machine code,
72 /// by considering all pointer types to be equivalent. Once identified,
73 /// MergeFunctions will fold them by replacing a call to one to a call to a
74 /// bitcast of the other.
75 ///
Nick Lewyckybe04fde2010-08-08 05:04:23 +000076 class MergeFunctions : public ModulePass {
77 public:
78 static char ID;
Owen Anderson90c579d2010-08-06 18:33:48 +000079 MergeFunctions() : ModulePass(ID) {}
Nick Lewycky579a0242008-11-02 05:52:50 +000080
81 bool runOnModule(Module &M);
Nick Lewyckybe04fde2010-08-08 05:04:23 +000082
83 private:
Nick Lewyckyf53de862010-08-31 05:53:05 +000084 /// MergeTwoFunctions - Merge two equivalent functions. Upon completion, G
85 /// is deleted.
86 void MergeTwoFunctions(Function *F, Function *G) const;
Nick Lewyckybe04fde2010-08-08 05:04:23 +000087
88 /// WriteThunk - Replace G with a simple tail call to bitcast(F). Also
89 /// replace direct uses of G with bitcast(F).
90 void WriteThunk(Function *F, Function *G) const;
91
92 TargetData *TD;
Nick Lewycky579a0242008-11-02 05:52:50 +000093 };
94}
95
96char MergeFunctions::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000097INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false);
Nick Lewycky579a0242008-11-02 05:52:50 +000098
99ModulePass *llvm::createMergeFunctionsPass() {
100 return new MergeFunctions();
101}
102
Nick Lewycky78d43302010-08-02 05:23:03 +0000103namespace {
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000104/// FunctionComparator - Compares two functions to determine whether or not
105/// they will generate machine code with the same behaviour. TargetData is
106/// used if available. The comparator always fails conservatively (erring on the
107/// side of claiming that two functions are different).
Nick Lewycky78d43302010-08-02 05:23:03 +0000108class FunctionComparator {
109public:
Nick Lewyckyf53de862010-08-31 05:53:05 +0000110 FunctionComparator(const TargetData *TD, const Function *F1,
111 const Function *F2)
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000112 : F1(F1), F2(F2), TD(TD), IDMap1Count(0), IDMap2Count(0) {}
Nick Lewycky287de602009-06-12 08:04:51 +0000113
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000114 /// Compare - test whether the two functions have equivalent behaviour.
Nick Lewycky78d43302010-08-02 05:23:03 +0000115 bool Compare();
116
117private:
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000118 /// Compare - test whether two basic blocks have equivalent behaviour.
Nick Lewycky78d43302010-08-02 05:23:03 +0000119 bool Compare(const BasicBlock *BB1, const BasicBlock *BB2);
120
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000121 /// Enumerate - Assign or look up previously assigned numbers for the two
122 /// values, and return whether the numbers are equal. Numbers are assigned in
123 /// the order visited.
Nick Lewycky78d43302010-08-02 05:23:03 +0000124 bool Enumerate(const Value *V1, const Value *V2);
125
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000126 /// isEquivalentOperation - Compare two Instructions for equivalence, similar
127 /// to Instruction::isSameOperationAs but with modifications to the type
128 /// comparison.
Nick Lewycky78d43302010-08-02 05:23:03 +0000129 bool isEquivalentOperation(const Instruction *I1,
130 const Instruction *I2) const;
131
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000132 /// isEquivalentGEP - Compare two GEPs for equivalent pointer arithmetic.
Nick Lewycky78d43302010-08-02 05:23:03 +0000133 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
134 bool isEquivalentGEP(const GetElementPtrInst *GEP1,
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000135 const GetElementPtrInst *GEP2) {
Nick Lewycky78d43302010-08-02 05:23:03 +0000136 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
137 }
138
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000139 /// isEquivalentType - Compare two Types, treating all pointer types as equal.
Nick Lewycky78d43302010-08-02 05:23:03 +0000140 bool isEquivalentType(const Type *Ty1, const Type *Ty2) const;
141
142 // The two functions undergoing comparison.
Nick Lewyckyf53de862010-08-31 05:53:05 +0000143 const Function *F1, *F2;
Nick Lewycky78d43302010-08-02 05:23:03 +0000144
Nick Lewyckyf53de862010-08-31 05:53:05 +0000145 const TargetData *TD;
Nick Lewycky78d43302010-08-02 05:23:03 +0000146
147 typedef DenseMap<const Value *, unsigned long> IDMap;
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000148 IDMap Map1, Map2;
149 unsigned long IDMap1Count, IDMap2Count;
Nick Lewycky78d43302010-08-02 05:23:03 +0000150};
151}
152
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000153/// isEquivalentType - any two pointers in the same address space are
154/// equivalent. Otherwise, standard type equivalence rules apply.
Nick Lewycky78d43302010-08-02 05:23:03 +0000155bool FunctionComparator::isEquivalentType(const Type *Ty1,
156 const Type *Ty2) const {
Nick Lewycky287de602009-06-12 08:04:51 +0000157 if (Ty1 == Ty2)
158 return true;
159 if (Ty1->getTypeID() != Ty2->getTypeID())
160 return false;
161
162 switch(Ty1->getTypeID()) {
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000163 default:
164 llvm_unreachable("Unknown type!");
Duncan Sands8246adc2010-07-07 07:48:00 +0000165 // Fall through in Release mode.
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000166 case Type::IntegerTyID:
167 case Type::OpaqueTyID:
168 // Ty1 == Ty2 would have returned true earlier.
169 return false;
170
Nick Lewycky287de602009-06-12 08:04:51 +0000171 case Type::VoidTyID:
172 case Type::FloatTyID:
173 case Type::DoubleTyID:
174 case Type::X86_FP80TyID:
175 case Type::FP128TyID:
176 case Type::PPC_FP128TyID:
177 case Type::LabelTyID:
178 case Type::MetadataTyID:
179 return true;
180
Nick Lewycky287de602009-06-12 08:04:51 +0000181 case Type::PointerTyID: {
182 const PointerType *PTy1 = cast<PointerType>(Ty1);
183 const PointerType *PTy2 = cast<PointerType>(Ty2);
184 return PTy1->getAddressSpace() == PTy2->getAddressSpace();
185 }
186
187 case Type::StructTyID: {
188 const StructType *STy1 = cast<StructType>(Ty1);
189 const StructType *STy2 = cast<StructType>(Ty2);
190 if (STy1->getNumElements() != STy2->getNumElements())
191 return false;
192
193 if (STy1->isPacked() != STy2->isPacked())
194 return false;
195
196 for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) {
197 if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i)))
198 return false;
199 }
200 return true;
201 }
202
203 case Type::FunctionTyID: {
204 const FunctionType *FTy1 = cast<FunctionType>(Ty1);
205 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
206 if (FTy1->getNumParams() != FTy2->getNumParams() ||
207 FTy1->isVarArg() != FTy2->isVarArg())
208 return false;
209
210 if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType()))
211 return false;
212
213 for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) {
214 if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i)))
215 return false;
216 }
217 return true;
218 }
219
Nick Lewycky394ce412010-07-16 06:31:12 +0000220 case Type::ArrayTyID: {
221 const ArrayType *ATy1 = cast<ArrayType>(Ty1);
222 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
223 return ATy1->getNumElements() == ATy2->getNumElements() &&
224 isEquivalentType(ATy1->getElementType(), ATy2->getElementType());
225 }
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000226
Nick Lewycky287de602009-06-12 08:04:51 +0000227 case Type::VectorTyID: {
Nick Lewycky394ce412010-07-16 06:31:12 +0000228 const VectorType *VTy1 = cast<VectorType>(Ty1);
229 const VectorType *VTy2 = cast<VectorType>(Ty2);
230 return VTy1->getNumElements() == VTy2->getNumElements() &&
231 isEquivalentType(VTy1->getElementType(), VTy2->getElementType());
Nick Lewycky287de602009-06-12 08:04:51 +0000232 }
233 }
234}
235
236/// isEquivalentOperation - determine whether the two operations are the same
237/// except that pointer-to-A and pointer-to-B are equivalent. This should be
Dan Gohman194ae782009-06-12 19:03:05 +0000238/// kept in sync with Instruction::isSameOperationAs.
Nick Lewycky78d43302010-08-02 05:23:03 +0000239bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
240 const Instruction *I2) const {
Nick Lewycky287de602009-06-12 08:04:51 +0000241 if (I1->getOpcode() != I2->getOpcode() ||
242 I1->getNumOperands() != I2->getNumOperands() ||
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000243 !isEquivalentType(I1->getType(), I2->getType()) ||
244 !I1->hasSameSubclassOptionalData(I2))
Nick Lewycky287de602009-06-12 08:04:51 +0000245 return false;
246
247 // We have two instructions of identical opcode and #operands. Check to see
248 // if all operands are the same type
249 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
250 if (!isEquivalentType(I1->getOperand(i)->getType(),
251 I2->getOperand(i)->getType()))
252 return false;
253
254 // Check special state that is a part of some instructions.
255 if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
256 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
257 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment();
258 if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
259 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
260 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment();
261 if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
262 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
263 if (const CallInst *CI = dyn_cast<CallInst>(I1))
264 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
265 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
266 CI->getAttributes().getRawPointer() ==
267 cast<CallInst>(I2)->getAttributes().getRawPointer();
268 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
269 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
270 CI->getAttributes().getRawPointer() ==
271 cast<InvokeInst>(I2)->getAttributes().getRawPointer();
272 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) {
273 if (IVI->getNumIndices() != cast<InsertValueInst>(I2)->getNumIndices())
274 return false;
275 for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i)
276 if (IVI->idx_begin()[i] != cast<InsertValueInst>(I2)->idx_begin()[i])
277 return false;
278 return true;
279 }
280 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) {
281 if (EVI->getNumIndices() != cast<ExtractValueInst>(I2)->getNumIndices())
282 return false;
283 for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i)
284 if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I2)->idx_begin()[i])
285 return false;
286 return true;
287 }
288
289 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000290}
291
Nick Lewycky78d43302010-08-02 05:23:03 +0000292/// isEquivalentGEP - determine whether two GEP operations perform the same
293/// underlying arithmetic.
294bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
295 const GEPOperator *GEP2) {
296 // When we have target data, we can reduce the GEP down to the value in bytes
297 // added to the address.
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000298 if (TD && GEP1->hasAllConstantIndices() && GEP2->hasAllConstantIndices()) {
Nick Lewycky78d43302010-08-02 05:23:03 +0000299 SmallVector<Value *, 8> Indices1(GEP1->idx_begin(), GEP1->idx_end());
300 SmallVector<Value *, 8> Indices2(GEP2->idx_begin(), GEP2->idx_end());
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000301 uint64_t Offset1 = TD->getIndexedOffset(GEP1->getPointerOperandType(),
302 Indices1.data(), Indices1.size());
303 uint64_t Offset2 = TD->getIndexedOffset(GEP2->getPointerOperandType(),
304 Indices2.data(), Indices2.size());
305 return Offset1 == Offset2;
Nick Lewycky579a0242008-11-02 05:52:50 +0000306 }
307
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000308 if (GEP1->getPointerOperand()->getType() !=
309 GEP2->getPointerOperand()->getType())
310 return false;
311
312 if (GEP1->getNumOperands() != GEP2->getNumOperands())
313 return false;
314
315 for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
Nick Lewycky78d43302010-08-02 05:23:03 +0000316 if (!Enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000317 return false;
318 }
319
320 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000321}
322
Nick Lewycky78d43302010-08-02 05:23:03 +0000323/// Enumerate - Compare two values used by the two functions under pair-wise
324/// comparison. If this is the first time the values are seen, they're added to
325/// the mapping so that we will detect mismatches on next use.
326bool FunctionComparator::Enumerate(const Value *V1, const Value *V2) {
327 // Check for function @f1 referring to itself and function @f2 referring to
328 // itself, or referring to each other, or both referring to either of them.
329 // They're all equivalent if the two functions are otherwise equivalent.
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000330 if (V1 == F1 && V2 == F2)
331 return true;
332 if (V1 == F2 && V2 == F1)
333 return true;
Nick Lewycky579a0242008-11-02 05:52:50 +0000334
Nick Lewycky78d43302010-08-02 05:23:03 +0000335 // TODO: constant expressions with GEP or references to F1 or F2.
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000336 if (isa<Constant>(V1))
337 return V1 == V2;
338
339 if (isa<InlineAsm>(V1) && isa<InlineAsm>(V2)) {
340 const InlineAsm *IA1 = cast<InlineAsm>(V1);
341 const InlineAsm *IA2 = cast<InlineAsm>(V2);
342 return IA1->getAsmString() == IA2->getAsmString() &&
343 IA1->getConstraintString() == IA2->getConstraintString();
344 }
345
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000346 unsigned long &ID1 = Map1[V1];
347 if (!ID1)
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000348 ID1 = ++IDMap1Count;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000349
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000350 unsigned long &ID2 = Map2[V2];
351 if (!ID2)
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000352 ID2 = ++IDMap2Count;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000353
354 return ID1 == ID2;
355}
356
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000357/// Compare - test whether two basic blocks have equivalent behaviour.
Nick Lewycky78d43302010-08-02 05:23:03 +0000358bool FunctionComparator::Compare(const BasicBlock *BB1, const BasicBlock *BB2) {
359 BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
360 BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
Nick Lewycky579a0242008-11-02 05:52:50 +0000361
362 do {
Nick Lewycky78d43302010-08-02 05:23:03 +0000363 if (!Enumerate(F1I, F2I))
Nick Lewycky579a0242008-11-02 05:52:50 +0000364 return false;
365
Nick Lewycky78d43302010-08-02 05:23:03 +0000366 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
367 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
368 if (!GEP2)
369 return false;
Nick Lewyckya142c932009-06-13 19:09:52 +0000370
Nick Lewycky78d43302010-08-02 05:23:03 +0000371 if (!Enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
Nick Lewycky911ae392010-05-13 06:45:13 +0000372 return false;
Nick Lewyckya142c932009-06-13 19:09:52 +0000373
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000374 if (!isEquivalentGEP(GEP1, GEP2))
Nick Lewycky911ae392010-05-13 06:45:13 +0000375 return false;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000376 } else {
Nick Lewycky78d43302010-08-02 05:23:03 +0000377 if (!isEquivalentOperation(F1I, F2I))
Nick Lewycky579a0242008-11-02 05:52:50 +0000378 return false;
379
Nick Lewycky78d43302010-08-02 05:23:03 +0000380 assert(F1I->getNumOperands() == F2I->getNumOperands());
381 for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
382 Value *OpF1 = F1I->getOperand(i);
383 Value *OpF2 = F2I->getOperand(i);
Nick Lewycky579a0242008-11-02 05:52:50 +0000384
Nick Lewycky78d43302010-08-02 05:23:03 +0000385 if (!Enumerate(OpF1, OpF2))
Nick Lewycky911ae392010-05-13 06:45:13 +0000386 return false;
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000387
Nick Lewycky78d43302010-08-02 05:23:03 +0000388 if (OpF1->getValueID() != OpF2->getValueID() ||
389 !isEquivalentType(OpF1->getType(), OpF2->getType()))
Nick Lewycky579a0242008-11-02 05:52:50 +0000390 return false;
391 }
Nick Lewycky579a0242008-11-02 05:52:50 +0000392 }
393
Nick Lewycky78d43302010-08-02 05:23:03 +0000394 ++F1I, ++F2I;
395 } while (F1I != F1E && F2I != F2E);
Nick Lewycky579a0242008-11-02 05:52:50 +0000396
Nick Lewycky78d43302010-08-02 05:23:03 +0000397 return F1I == F1E && F2I == F2E;
Nick Lewycky579a0242008-11-02 05:52:50 +0000398}
399
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000400/// Compare - test whether the two functions have equivalent behaviour.
Nick Lewycky78d43302010-08-02 05:23:03 +0000401bool FunctionComparator::Compare() {
Nick Lewycky579a0242008-11-02 05:52:50 +0000402 // We need to recheck everything, but check the things that weren't included
403 // in the hash first.
404
Nick Lewycky78d43302010-08-02 05:23:03 +0000405 if (F1->getAttributes() != F2->getAttributes())
Nick Lewycky579a0242008-11-02 05:52:50 +0000406 return false;
407
Nick Lewycky78d43302010-08-02 05:23:03 +0000408 if (F1->hasGC() != F2->hasGC())
Nick Lewycky579a0242008-11-02 05:52:50 +0000409 return false;
410
Nick Lewycky78d43302010-08-02 05:23:03 +0000411 if (F1->hasGC() && F1->getGC() != F2->getGC())
Nick Lewycky579a0242008-11-02 05:52:50 +0000412 return false;
413
Nick Lewycky78d43302010-08-02 05:23:03 +0000414 if (F1->hasSection() != F2->hasSection())
Nick Lewycky579a0242008-11-02 05:52:50 +0000415 return false;
416
Nick Lewycky78d43302010-08-02 05:23:03 +0000417 if (F1->hasSection() && F1->getSection() != F2->getSection())
Nick Lewycky579a0242008-11-02 05:52:50 +0000418 return false;
419
Nick Lewycky78d43302010-08-02 05:23:03 +0000420 if (F1->isVarArg() != F2->isVarArg())
Nick Lewycky287de602009-06-12 08:04:51 +0000421 return false;
422
Nick Lewycky579a0242008-11-02 05:52:50 +0000423 // TODO: if it's internal and only used in direct calls, we could handle this
424 // case too.
Nick Lewycky78d43302010-08-02 05:23:03 +0000425 if (F1->getCallingConv() != F2->getCallingConv())
Nick Lewycky579a0242008-11-02 05:52:50 +0000426 return false;
427
Nick Lewycky78d43302010-08-02 05:23:03 +0000428 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
Nick Lewycky579a0242008-11-02 05:52:50 +0000429 return false;
430
Nick Lewycky78d43302010-08-02 05:23:03 +0000431 assert(F1->arg_size() == F2->arg_size() &&
Nick Lewycky579a0242008-11-02 05:52:50 +0000432 "Identical functions have a different number of args.");
433
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000434 // Visit the arguments so that they get enumerated in the order they're
435 // passed in.
Nick Lewycky78d43302010-08-02 05:23:03 +0000436 for (Function::const_arg_iterator f1i = F1->arg_begin(),
437 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
438 if (!Enumerate(f1i, f2i))
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000439 llvm_unreachable("Arguments repeat");
Nick Lewycky579a0242008-11-02 05:52:50 +0000440 }
441
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000442 // We do a CFG-ordered walk since the actual ordering of the blocks in the
443 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewycky78d43302010-08-02 05:23:03 +0000444 // functions, then takes each block from each terminator in order. As an
445 // artifact, this also means that unreachable blocks are ignored.
446 SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
447 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000448
Nick Lewycky78d43302010-08-02 05:23:03 +0000449 F1BBs.push_back(&F1->getEntryBlock());
450 F2BBs.push_back(&F2->getEntryBlock());
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000451
Nick Lewycky78d43302010-08-02 05:23:03 +0000452 VisitedBBs.insert(F1BBs[0]);
453 while (!F1BBs.empty()) {
454 const BasicBlock *F1BB = F1BBs.pop_back_val();
455 const BasicBlock *F2BB = F2BBs.pop_back_val();
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000456
Nick Lewycky78d43302010-08-02 05:23:03 +0000457 if (!Enumerate(F1BB, F2BB) || !Compare(F1BB, F2BB))
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000458 return false;
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000459
Nick Lewycky78d43302010-08-02 05:23:03 +0000460 const TerminatorInst *F1TI = F1BB->getTerminator();
461 const TerminatorInst *F2TI = F2BB->getTerminator();
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000462
Nick Lewycky78d43302010-08-02 05:23:03 +0000463 assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
464 for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
465 if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
Nick Lewycky911ae392010-05-13 06:45:13 +0000466 continue;
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000467
Nick Lewycky78d43302010-08-02 05:23:03 +0000468 F1BBs.push_back(F1TI->getSuccessor(i));
469 F2BBs.push_back(F2TI->getSuccessor(i));
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000470 }
471 }
Nick Lewycky579a0242008-11-02 05:52:50 +0000472 return true;
473}
474
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000475/// WriteThunk - Replace G with a simple tail call to bitcast(F). Also replace
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000476/// direct uses of G with bitcast(F).
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000477void MergeFunctions::WriteThunk(Function *F, Function *G) const {
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000478 if (!G->mayBeOverridden()) {
479 // Redirect direct callers of G to F.
480 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
481 for (Value::use_iterator UI = G->use_begin(), UE = G->use_end();
482 UI != UE;) {
483 Value::use_iterator TheIter = UI;
484 ++UI;
485 CallSite CS(*TheIter);
486 if (CS && CS.isCallee(TheIter))
487 TheIter.getUse().set(BitcastF);
488 }
489 }
490
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000491 // If G was internal then we may have replaced all uses if G with F. If so,
492 // stop here and delete G. There's no need for a thunk.
493 if (G->hasLocalLinkage() && G->use_empty()) {
494 G->eraseFromParent();
495 return;
496 }
497
Nick Lewycky8728d7a2009-06-12 15:56:56 +0000498 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
499 G->getParent());
Owen Anderson1d0be152009-08-13 21:58:54 +0000500 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000501 IRBuilder<false> Builder(BB);
Nick Lewycky287de602009-06-12 08:04:51 +0000502
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000503 SmallVector<Value *, 16> Args;
Nick Lewycky287de602009-06-12 08:04:51 +0000504 unsigned i = 0;
505 const FunctionType *FFTy = F->getFunctionType();
506 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
507 AI != AE; ++AI) {
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000508 Args.push_back(Builder.CreateBitCast(AI, FFTy->getParamType(i)));
Nick Lewycky287de602009-06-12 08:04:51 +0000509 ++i;
510 }
511
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000512 CallInst *CI = Builder.CreateCall(F, Args.begin(), Args.end());
Nick Lewycky287de602009-06-12 08:04:51 +0000513 CI->setTailCall();
Nick Lewyckyb3c36c92009-06-12 16:04:00 +0000514 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerf0127052010-01-05 13:12:22 +0000515 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000516 Builder.CreateRetVoid();
Nick Lewycky287de602009-06-12 08:04:51 +0000517 } else {
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000518 Builder.CreateRet(Builder.CreateBitCast(CI, NewG->getReturnType()));
Nick Lewycky287de602009-06-12 08:04:51 +0000519 }
520
521 NewG->copyAttributesFrom(G);
522 NewG->takeName(G);
523 G->replaceAllUsesWith(NewG);
524 G->eraseFromParent();
Nick Lewycky287de602009-06-12 08:04:51 +0000525}
526
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000527/// MergeTwoFunctions - Merge two equivalent functions. Upon completion,
Nick Lewyckyf53de862010-08-31 05:53:05 +0000528/// Function G is deleted.
529void MergeFunctions::MergeTwoFunctions(Function *F, Function *G) const {
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000530 if (F->isWeakForLinker()) {
531 assert(G->isWeakForLinker());
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000532
533 // Make them both thunks to the same internal function.
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000534 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
535 F->getParent());
536 H->copyAttributesFrom(F);
537 H->takeName(F);
538 F->replaceAllUsesWith(H);
539
Nick Lewycky32218342010-08-09 21:03:28 +0000540 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
541
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000542 WriteThunk(F, G);
543 WriteThunk(F, H);
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000544
Nick Lewycky32218342010-08-09 21:03:28 +0000545 F->setAlignment(MaxAlignment);
Nick Lewycky33ab0b12010-05-13 05:48:45 +0000546 F->setLinkage(GlobalValue::InternalLinkage);
Nick Lewyckyc9dcbed2010-08-06 07:21:30 +0000547 } else {
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000548 WriteThunk(F, G);
Nick Lewycky6feb3332008-11-02 16:46:26 +0000549 }
550
Nick Lewycky287de602009-06-12 08:04:51 +0000551 ++NumFunctionsMerged;
Nick Lewycky579a0242008-11-02 05:52:50 +0000552}
553
Nick Lewyckyf53de862010-08-31 05:53:05 +0000554static unsigned ProfileFunction(const Function *F) {
555 const FunctionType *FTy = F->getFunctionType();
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000556
Nick Lewyckyf53de862010-08-31 05:53:05 +0000557 FoldingSetNodeID ID;
558 ID.AddInteger(F->size());
559 ID.AddInteger(F->getCallingConv());
560 ID.AddBoolean(F->hasGC());
561 ID.AddBoolean(FTy->isVarArg());
562 ID.AddInteger(FTy->getReturnType()->getTypeID());
563 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
564 ID.AddInteger(FTy->getParamType(i)->getTypeID());
565 return ID.ComputeHash();
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000566}
Nick Lewycky579a0242008-11-02 05:52:50 +0000567
Nick Lewyckyf53de862010-08-31 05:53:05 +0000568class ComparableFunction {
569public:
570 ComparableFunction(Function *Func, TargetData *TD)
571 : Func(Func), Hash(ProfileFunction(Func)), TD(TD) {}
572
573 AssertingVH<Function> const Func;
574 const unsigned Hash;
575 TargetData * const TD;
576};
577
578struct MergeFunctionsEqualityInfo {
579 static ComparableFunction *getEmptyKey() {
580 return reinterpret_cast<ComparableFunction*>(0);
581 }
582 static ComparableFunction *getTombstoneKey() {
583 return reinterpret_cast<ComparableFunction*>(-1);
584 }
585 static unsigned getHashValue(const ComparableFunction *CF) {
586 return CF->Hash;
587 }
588 static bool isEqual(const ComparableFunction *LHS,
589 const ComparableFunction *RHS) {
590 if (LHS == RHS)
591 return true;
592 if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
593 RHS == getEmptyKey() || RHS == getTombstoneKey())
594 return false;
595 assert(LHS->TD == RHS->TD && "Comparing functions for different targets");
596 return FunctionComparator(LHS->TD, LHS->Func, RHS->Func).Compare();
597 }
598};
599
Nick Lewycky579a0242008-11-02 05:52:50 +0000600bool MergeFunctions::runOnModule(Module &M) {
601 bool Changed = false;
602
Nick Lewyckybe04fde2010-08-08 05:04:23 +0000603 TD = getAnalysisIfAvailable<TargetData>();
Nick Lewycky579a0242008-11-02 05:52:50 +0000604
Nick Lewyckyf53de862010-08-31 05:53:05 +0000605 typedef DenseSet<ComparableFunction *, MergeFunctionsEqualityInfo> FnSetType;
606 FnSetType FnSet;
607 for (Module::iterator F = M.begin(), E = M.end(); F != E;) {
608 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
609 ++F;
610 continue;
Nick Lewycky579a0242008-11-02 05:52:50 +0000611 }
Nick Lewycky579a0242008-11-02 05:52:50 +0000612
Nick Lewyckyf53de862010-08-31 05:53:05 +0000613 ComparableFunction *NewF = new ComparableFunction(F, TD);
614 ++F;
615 std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
616 if (!Result.second) {
617 ComparableFunction *&OldF = *Result.first;
618 assert(OldF && "Expected a hash collision");
619
620 // NewF will be deleted in favour of OldF unless NewF is strong and OldF
621 // is weak in which case swap them to keep the strong definition.
622
623 if (OldF->Func->isWeakForLinker() && !NewF->Func->isWeakForLinker())
624 std::swap(OldF, NewF);
625
626 DEBUG(dbgs() << " " << OldF->Func->getName() << " == "
627 << NewF->Func->getName() << '\n');
628
629 Changed = true;
630 Function *DeleteF = NewF->Func;
631 delete NewF;
632 MergeTwoFunctions(OldF->Func, DeleteF);
633 }
634 }
635
636 DeleteContainerPointers(FnSet);
Nick Lewycky579a0242008-11-02 05:52:50 +0000637 return Changed;
638}