MergeFunctions.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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. If both functions are
  21. // overridable, we move the functionality into a new internal function and
  22. // leave two overridable thunks to it.
  23. //
  24. //===----------------------------------------------------------------------===//
  25. //
  26. // Future work:
  27. //
  28. // * 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
  32. // and call, this is irrelevant, and we'd like to fold such functions.
  33. //
  34. // * switch from n^2 pair-wise comparisons to an n-way comparison for each
  35. // bucket.
  36. //
  37. // * be smarter about bitcasts.
  38. //
  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 look through bitcasts.
  43. //
  44. //===----------------------------------------------------------------------===//
  45. #define DEBUG_TYPE "mergefunc"
  46. #include "llvm/Transforms/IPO.h"
  47. #include "llvm/ADT/DenseSet.h"
  48. #include "llvm/ADT/FoldingSet.h"
  49. #include "llvm/ADT/STLExtras.h"
  50. #include "llvm/ADT/SmallSet.h"
  51. #include "llvm/ADT/Statistic.h"
  52. #include "llvm/IR/Constants.h"
  53. #include "llvm/IR/DataLayout.h"
  54. #include "llvm/IR/IRBuilder.h"
  55. #include "llvm/IR/InlineAsm.h"
  56. #include "llvm/IR/Instructions.h"
  57. #include "llvm/IR/LLVMContext.h"
  58. #include "llvm/IR/Module.h"
  59. #include "llvm/IR/Operator.h"
  60. #include "llvm/Pass.h"
  61. #include "llvm/Support/CallSite.h"
  62. #include "llvm/Support/Debug.h"
  63. #include "llvm/Support/ErrorHandling.h"
  64. #include "llvm/Support/ValueHandle.h"
  65. #include "llvm/Support/raw_ostream.h"
  66. #include <vector>
  67. using namespace llvm;
  68. STATISTIC(NumFunctionsMerged, "Number of functions merged");
  69. STATISTIC(NumThunksWritten, "Number of thunks generated");
  70. STATISTIC(NumAliasesWritten, "Number of aliases generated");
  71. STATISTIC(NumDoubleWeak, "Number of new functions created");
  72. /// Returns the type id for a type to be hashed. We turn pointer types into
  73. /// integers here because the actual compare logic below considers pointers and
  74. /// integers of the same size as equal.
  75. static Type::TypeID getTypeIDForHash(Type *Ty) {
  76. if (Ty->isPointerTy())
  77. return Type::IntegerTyID;
  78. return Ty->getTypeID();
  79. }
  80. /// Creates a hash-code for the function which is the same for any two
  81. /// functions that will compare equal, without looking at the instructions
  82. /// inside the function.
  83. static unsigned profileFunction(const Function *F) {
  84. FunctionType *FTy = F->getFunctionType();
  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(getTypeIDForHash(FTy->getReturnType()));
  91. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  92. ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
  93. return ID.ComputeHash();
  94. }
  95. namespace {
  96. /// ComparableFunction - A struct that pairs together functions with a
  97. /// DataLayout so that we can keep them together as elements in the DenseSet.
  98. class ComparableFunction {
  99. public:
  100. static const ComparableFunction EmptyKey;
  101. static const ComparableFunction TombstoneKey;
  102. static DataLayout * const LookupOnly;
  103. ComparableFunction(Function *Func, DataLayout *TD)
  104. : Func(Func), Hash(profileFunction(Func)), TD(TD) {}
  105. Function *getFunc() const { return Func; }
  106. unsigned getHash() const { return Hash; }
  107. DataLayout *getTD() const { return TD; }
  108. // Drops AssertingVH reference to the function. Outside of debug mode, this
  109. // does nothing.
  110. void release() {
  111. assert(Func &&
  112. "Attempted to release function twice, or release empty/tombstone!");
  113. Func = NULL;
  114. }
  115. private:
  116. explicit ComparableFunction(unsigned Hash)
  117. : Func(NULL), Hash(Hash), TD(NULL) {}
  118. AssertingVH<Function> Func;
  119. unsigned Hash;
  120. DataLayout *TD;
  121. };
  122. const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
  123. const ComparableFunction ComparableFunction::TombstoneKey =
  124. ComparableFunction(1);
  125. DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
  126. }
  127. namespace llvm {
  128. template <>
  129. struct DenseMapInfo<ComparableFunction> {
  130. static ComparableFunction getEmptyKey() {
  131. return ComparableFunction::EmptyKey;
  132. }
  133. static ComparableFunction getTombstoneKey() {
  134. return ComparableFunction::TombstoneKey;
  135. }
  136. static unsigned getHashValue(const ComparableFunction &CF) {
  137. return CF.getHash();
  138. }
  139. static bool isEqual(const ComparableFunction &LHS,
  140. const ComparableFunction &RHS);
  141. };
  142. }
  143. namespace {
  144. /// FunctionComparator - Compares two functions to determine whether or not
  145. /// they will generate machine code with the same behaviour. DataLayout is
  146. /// used if available. The comparator always fails conservatively (erring on the
  147. /// side of claiming that two functions are different).
  148. class FunctionComparator {
  149. public:
  150. FunctionComparator(const DataLayout *TD, const Function *F1,
  151. const Function *F2)
  152. : F1(F1), F2(F2), TD(TD) {}
  153. /// Test whether the two functions have equivalent behaviour.
  154. bool compare();
  155. private:
  156. /// Test whether two basic blocks have equivalent behaviour.
  157. bool compare(const BasicBlock *BB1, const BasicBlock *BB2);
  158. /// Assign or look up previously assigned numbers for the two values, and
  159. /// return whether the numbers are equal. Numbers are assigned in the order
  160. /// visited.
  161. bool enumerate(const Value *V1, const Value *V2);
  162. /// Compare two Instructions for equivalence, similar to
  163. /// Instruction::isSameOperationAs but with modifications to the type
  164. /// comparison.
  165. bool isEquivalentOperation(const Instruction *I1,
  166. const Instruction *I2) const;
  167. /// Compare two GEPs for equivalent pointer arithmetic.
  168. bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
  169. bool isEquivalentGEP(const GetElementPtrInst *GEP1,
  170. const GetElementPtrInst *GEP2) {
  171. return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
  172. }
  173. /// Compare two Types, treating all pointer types as equal.
  174. bool isEquivalentType(Type *Ty1, Type *Ty2) const;
  175. // The two functions undergoing comparison.
  176. const Function *F1, *F2;
  177. const DataLayout *TD;
  178. DenseMap<const Value *, const Value *> id_map;
  179. DenseSet<const Value *> seen_values;
  180. };
  181. }
  182. // Any two pointers in the same address space are equivalent, intptr_t and
  183. // pointers are equivalent. Otherwise, standard type equivalence rules apply.
  184. bool FunctionComparator::isEquivalentType(Type *Ty1, Type *Ty2) const {
  185. PointerType *PTy1 = dyn_cast<PointerType>(Ty1);
  186. PointerType *PTy2 = dyn_cast<PointerType>(Ty2);
  187. if (TD) {
  188. if (PTy1 && PTy1->getAddressSpace() == 0) Ty1 = TD->getIntPtrType(Ty1);
  189. if (PTy2 && PTy2->getAddressSpace() == 0) Ty2 = TD->getIntPtrType(Ty2);
  190. }
  191. if (Ty1 == Ty2)
  192. return true;
  193. if (Ty1->getTypeID() != Ty2->getTypeID())
  194. return false;
  195. switch (Ty1->getTypeID()) {
  196. default:
  197. llvm_unreachable("Unknown type!");
  198. // Fall through in Release mode.
  199. case Type::IntegerTyID:
  200. case Type::VectorTyID:
  201. // Ty1 == Ty2 would have returned true earlier.
  202. return false;
  203. case Type::VoidTyID:
  204. case Type::FloatTyID:
  205. case Type::DoubleTyID:
  206. case Type::X86_FP80TyID:
  207. case Type::FP128TyID:
  208. case Type::PPC_FP128TyID:
  209. case Type::LabelTyID:
  210. case Type::MetadataTyID:
  211. return true;
  212. case Type::PointerTyID: {
  213. assert(PTy1 && PTy2 && "Both types must be pointers here.");
  214. return PTy1->getAddressSpace() == PTy2->getAddressSpace();
  215. }
  216. case Type::StructTyID: {
  217. StructType *STy1 = cast<StructType>(Ty1);
  218. StructType *STy2 = cast<StructType>(Ty2);
  219. if (STy1->getNumElements() != STy2->getNumElements())
  220. return false;
  221. if (STy1->isPacked() != STy2->isPacked())
  222. return false;
  223. for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) {
  224. if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i)))
  225. return false;
  226. }
  227. return true;
  228. }
  229. case Type::FunctionTyID: {
  230. FunctionType *FTy1 = cast<FunctionType>(Ty1);
  231. FunctionType *FTy2 = cast<FunctionType>(Ty2);
  232. if (FTy1->getNumParams() != FTy2->getNumParams() ||
  233. FTy1->isVarArg() != FTy2->isVarArg())
  234. return false;
  235. if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType()))
  236. return false;
  237. for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) {
  238. if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i)))
  239. return false;
  240. }
  241. return true;
  242. }
  243. case Type::ArrayTyID: {
  244. ArrayType *ATy1 = cast<ArrayType>(Ty1);
  245. ArrayType *ATy2 = cast<ArrayType>(Ty2);
  246. return ATy1->getNumElements() == ATy2->getNumElements() &&
  247. isEquivalentType(ATy1->getElementType(), ATy2->getElementType());
  248. }
  249. }
  250. }
  251. // Determine whether the two operations are the same except that pointer-to-A
  252. // and pointer-to-B are equivalent. This should be kept in sync with
  253. // Instruction::isSameOperationAs.
  254. bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
  255. const Instruction *I2) const {
  256. // Differences from Instruction::isSameOperationAs:
  257. // * replace type comparison with calls to isEquivalentType.
  258. // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
  259. // * because of the above, we don't test for the tail bit on calls later on
  260. if (I1->getOpcode() != I2->getOpcode() ||
  261. I1->getNumOperands() != I2->getNumOperands() ||
  262. !isEquivalentType(I1->getType(), I2->getType()) ||
  263. !I1->hasSameSubclassOptionalData(I2))
  264. return false;
  265. // We have two instructions of identical opcode and #operands. Check to see
  266. // if all operands are the same type
  267. for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
  268. if (!isEquivalentType(I1->getOperand(i)->getType(),
  269. I2->getOperand(i)->getType()))
  270. return false;
  271. // Check special state that is a part of some instructions.
  272. if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
  273. return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
  274. LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() &&
  275. LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
  276. LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
  277. if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
  278. return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
  279. SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() &&
  280. SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
  281. SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
  282. if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
  283. return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
  284. if (const CallInst *CI = dyn_cast<CallInst>(I1))
  285. return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
  286. CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
  287. if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
  288. return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
  289. CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes();
  290. if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
  291. return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
  292. if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
  293. return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
  294. if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
  295. return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
  296. FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
  297. if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
  298. return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
  299. CXI->getOrdering() == cast<AtomicCmpXchgInst>(I2)->getOrdering() &&
  300. CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
  301. if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
  302. return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
  303. RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
  304. RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
  305. RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
  306. return true;
  307. }
  308. // Determine whether two GEP operations perform the same underlying arithmetic.
  309. bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
  310. const GEPOperator *GEP2) {
  311. unsigned AS = GEP1->getPointerAddressSpace();
  312. if (AS != GEP2->getPointerAddressSpace())
  313. return false;
  314. if (TD) {
  315. // When we have target data, we can reduce the GEP down to the value in bytes
  316. // added to the address.
  317. unsigned BitWidth = TD ? TD->getPointerSizeInBits(AS) : 1;
  318. APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0);
  319. if (GEP1->accumulateConstantOffset(*TD, Offset1) &&
  320. GEP2->accumulateConstantOffset(*TD, Offset2)) {
  321. return Offset1 == Offset2;
  322. }
  323. }
  324. if (GEP1->getPointerOperand()->getType() !=
  325. GEP2->getPointerOperand()->getType())
  326. return false;
  327. if (GEP1->getNumOperands() != GEP2->getNumOperands())
  328. return false;
  329. for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
  330. if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
  331. return false;
  332. }
  333. return true;
  334. }
  335. // Compare two values used by the two functions under pair-wise comparison. If
  336. // this is the first time the values are seen, they're added to the mapping so
  337. // that we will detect mismatches on next use.
  338. bool FunctionComparator::enumerate(const Value *V1, const Value *V2) {
  339. // Check for function @f1 referring to itself and function @f2 referring to
  340. // itself, or referring to each other, or both referring to either of them.
  341. // They're all equivalent if the two functions are otherwise equivalent.
  342. if (V1 == F1 && V2 == F2)
  343. return true;
  344. if (V1 == F2 && V2 == F1)
  345. return true;
  346. if (const Constant *C1 = dyn_cast<Constant>(V1)) {
  347. if (V1 == V2) return true;
  348. const Constant *C2 = dyn_cast<Constant>(V2);
  349. if (!C2) return false;
  350. // TODO: constant expressions with GEP or references to F1 or F2.
  351. if (C1->isNullValue() && C2->isNullValue() &&
  352. isEquivalentType(C1->getType(), C2->getType()))
  353. return true;
  354. // Try bitcasting C2 to C1's type. If the bitcast is legal and returns C1
  355. // then they must have equal bit patterns.
  356. return C1->getType()->canLosslesslyBitCastTo(C2->getType()) &&
  357. C1 == ConstantExpr::getBitCast(const_cast<Constant*>(C2), C1->getType());
  358. }
  359. if (isa<InlineAsm>(V1) || isa<InlineAsm>(V2))
  360. return V1 == V2;
  361. // Check that V1 maps to V2. If we find a value that V1 maps to then we simply
  362. // check whether it's equal to V2. When there is no mapping then we need to
  363. // ensure that V2 isn't already equivalent to something else. For this
  364. // purpose, we track the V2 values in a set.
  365. const Value *&map_elem = id_map[V1];
  366. if (map_elem)
  367. return map_elem == V2;
  368. if (!seen_values.insert(V2).second)
  369. return false;
  370. map_elem = V2;
  371. return true;
  372. }
  373. // Test whether two basic blocks have equivalent behaviour.
  374. bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) {
  375. BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
  376. BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
  377. do {
  378. if (!enumerate(F1I, F2I))
  379. return false;
  380. if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
  381. const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
  382. if (!GEP2)
  383. return false;
  384. if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
  385. return false;
  386. if (!isEquivalentGEP(GEP1, GEP2))
  387. return false;
  388. } else {
  389. if (!isEquivalentOperation(F1I, F2I))
  390. return false;
  391. assert(F1I->getNumOperands() == F2I->getNumOperands());
  392. for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
  393. Value *OpF1 = F1I->getOperand(i);
  394. Value *OpF2 = F2I->getOperand(i);
  395. if (!enumerate(OpF1, OpF2))
  396. return false;
  397. if (OpF1->getValueID() != OpF2->getValueID() ||
  398. !isEquivalentType(OpF1->getType(), OpF2->getType()))
  399. return false;
  400. }
  401. }
  402. ++F1I, ++F2I;
  403. } while (F1I != F1E && F2I != F2E);
  404. return F1I == F1E && F2I == F2E;
  405. }
  406. // Test whether the two functions have equivalent behaviour.
  407. bool FunctionComparator::compare() {
  408. // We need to recheck everything, but check the things that weren't included
  409. // in the hash first.
  410. if (F1->getAttributes() != F2->getAttributes())
  411. return false;
  412. if (F1->hasGC() != F2->hasGC())
  413. return false;
  414. if (F1->hasGC() && F1->getGC() != F2->getGC())
  415. return false;
  416. if (F1->hasSection() != F2->hasSection())
  417. return false;
  418. if (F1->hasSection() && F1->getSection() != F2->getSection())
  419. return false;
  420. if (F1->isVarArg() != F2->isVarArg())
  421. return false;
  422. // TODO: if it's internal and only used in direct calls, we could handle this
  423. // case too.
  424. if (F1->getCallingConv() != F2->getCallingConv())
  425. return false;
  426. if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
  427. return false;
  428. assert(F1->arg_size() == F2->arg_size() &&
  429. "Identically typed functions have different numbers of args!");
  430. // Visit the arguments so that they get enumerated in the order they're
  431. // passed in.
  432. for (Function::const_arg_iterator f1i = F1->arg_begin(),
  433. f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
  434. if (!enumerate(f1i, f2i))
  435. llvm_unreachable("Arguments repeat!");
  436. }
  437. // We do a CFG-ordered walk since the actual ordering of the blocks in the
  438. // linked list is immaterial. Our walk starts at the entry block for both
  439. // functions, then takes each block from each terminator in order. As an
  440. // artifact, this also means that unreachable blocks are ignored.
  441. SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
  442. SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
  443. F1BBs.push_back(&F1->getEntryBlock());
  444. F2BBs.push_back(&F2->getEntryBlock());
  445. VisitedBBs.insert(F1BBs[0]);
  446. while (!F1BBs.empty()) {
  447. const BasicBlock *F1BB = F1BBs.pop_back_val();
  448. const BasicBlock *F2BB = F2BBs.pop_back_val();
  449. if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB))
  450. return false;
  451. const TerminatorInst *F1TI = F1BB->getTerminator();
  452. const TerminatorInst *F2TI = F2BB->getTerminator();
  453. assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
  454. for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
  455. if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
  456. continue;
  457. F1BBs.push_back(F1TI->getSuccessor(i));
  458. F2BBs.push_back(F2TI->getSuccessor(i));
  459. }
  460. }
  461. return true;
  462. }
  463. namespace {
  464. /// MergeFunctions finds functions which will generate identical machine code,
  465. /// by considering all pointer types to be equivalent. Once identified,
  466. /// MergeFunctions will fold them by replacing a call to one to a call to a
  467. /// bitcast of the other.
  468. ///
  469. class MergeFunctions : public ModulePass {
  470. public:
  471. static char ID;
  472. MergeFunctions()
  473. : ModulePass(ID), HasGlobalAliases(false) {
  474. initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
  475. }
  476. bool runOnModule(Module &M);
  477. private:
  478. typedef DenseSet<ComparableFunction> FnSetType;
  479. /// A work queue of functions that may have been modified and should be
  480. /// analyzed again.
  481. std::vector<WeakVH> Deferred;
  482. /// Insert a ComparableFunction into the FnSet, or merge it away if it's
  483. /// equal to one that's already present.
  484. bool insert(ComparableFunction &NewF);
  485. /// Remove a Function from the FnSet and queue it up for a second sweep of
  486. /// analysis.
  487. void remove(Function *F);
  488. /// Find the functions that use this Value and remove them from FnSet and
  489. /// queue the functions.
  490. void removeUsers(Value *V);
  491. /// Replace all direct calls of Old with calls of New. Will bitcast New if
  492. /// necessary to make types match.
  493. void replaceDirectCallers(Function *Old, Function *New);
  494. /// Merge two equivalent functions. Upon completion, G may be deleted, or may
  495. /// be converted into a thunk. In either case, it should never be visited
  496. /// again.
  497. void mergeTwoFunctions(Function *F, Function *G);
  498. /// Replace G with a thunk or an alias to F. Deletes G.
  499. void writeThunkOrAlias(Function *F, Function *G);
  500. /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
  501. /// of G with bitcast(F). Deletes G.
  502. void writeThunk(Function *F, Function *G);
  503. /// Replace G with an alias to F. Deletes G.
  504. void writeAlias(Function *F, Function *G);
  505. /// The set of all distinct functions. Use the insert() and remove() methods
  506. /// to modify it.
  507. FnSetType FnSet;
  508. /// DataLayout for more accurate GEP comparisons. May be NULL.
  509. DataLayout *TD;
  510. /// Whether or not the target supports global aliases.
  511. bool HasGlobalAliases;
  512. };
  513. } // end anonymous namespace
  514. char MergeFunctions::ID = 0;
  515. INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
  516. ModulePass *llvm::createMergeFunctionsPass() {
  517. return new MergeFunctions();
  518. }
  519. bool MergeFunctions::runOnModule(Module &M) {
  520. bool Changed = false;
  521. TD = getAnalysisIfAvailable<DataLayout>();
  522. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
  523. if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
  524. Deferred.push_back(WeakVH(I));
  525. }
  526. FnSet.resize(Deferred.size());
  527. do {
  528. std::vector<WeakVH> Worklist;
  529. Deferred.swap(Worklist);
  530. DEBUG(dbgs() << "size of module: " << M.size() << '\n');
  531. DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
  532. // Insert only strong functions and merge them. Strong function merging
  533. // always deletes one of them.
  534. for (std::vector<WeakVH>::iterator I = Worklist.begin(),
  535. E = Worklist.end(); I != E; ++I) {
  536. if (!*I) continue;
  537. Function *F = cast<Function>(*I);
  538. if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
  539. !F->mayBeOverridden()) {
  540. ComparableFunction CF = ComparableFunction(F, TD);
  541. Changed |= insert(CF);
  542. }
  543. }
  544. // Insert only weak functions and merge them. By doing these second we
  545. // create thunks to the strong function when possible. When two weak
  546. // functions are identical, we create a new strong function with two weak
  547. // weak thunks to it which are identical but not mergable.
  548. for (std::vector<WeakVH>::iterator I = Worklist.begin(),
  549. E = Worklist.end(); I != E; ++I) {
  550. if (!*I) continue;
  551. Function *F = cast<Function>(*I);
  552. if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
  553. F->mayBeOverridden()) {
  554. ComparableFunction CF = ComparableFunction(F, TD);
  555. Changed |= insert(CF);
  556. }
  557. }
  558. DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
  559. } while (!Deferred.empty());
  560. FnSet.clear();
  561. return Changed;
  562. }
  563. bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
  564. const ComparableFunction &RHS) {
  565. if (LHS.getFunc() == RHS.getFunc() &&
  566. LHS.getHash() == RHS.getHash())
  567. return true;
  568. if (!LHS.getFunc() || !RHS.getFunc())
  569. return false;
  570. // One of these is a special "underlying pointer comparison only" object.
  571. if (LHS.getTD() == ComparableFunction::LookupOnly ||
  572. RHS.getTD() == ComparableFunction::LookupOnly)
  573. return false;
  574. assert(LHS.getTD() == RHS.getTD() &&
  575. "Comparing functions for different targets");
  576. return FunctionComparator(LHS.getTD(), LHS.getFunc(),
  577. RHS.getFunc()).compare();
  578. }
  579. // Replace direct callers of Old with New.
  580. void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
  581. Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
  582. for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
  583. UI != UE;) {
  584. Value::use_iterator TheIter = UI;
  585. ++UI;
  586. CallSite CS(*TheIter);
  587. if (CS && CS.isCallee(TheIter)) {
  588. remove(CS.getInstruction()->getParent()->getParent());
  589. TheIter.getUse().set(BitcastNew);
  590. }
  591. }
  592. }
  593. // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
  594. void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
  595. if (HasGlobalAliases && G->hasUnnamedAddr()) {
  596. if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
  597. G->hasWeakLinkage()) {
  598. writeAlias(F, G);
  599. return;
  600. }
  601. }
  602. writeThunk(F, G);
  603. }
  604. // Helper for writeThunk,
  605. // Selects proper bitcast operation,
  606. // but a bit simpler then CastInst::getCastOpcode.
  607. static Value* createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
  608. Type *SrcTy = V->getType();
  609. if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
  610. return Builder.CreateIntToPtr(V, DestTy);
  611. else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
  612. return Builder.CreatePtrToInt(V, DestTy);
  613. else
  614. return Builder.CreateBitCast(V, DestTy);
  615. }
  616. // Replace G with a simple tail call to bitcast(F). Also replace direct uses
  617. // of G with bitcast(F). Deletes G.
  618. void MergeFunctions::writeThunk(Function *F, Function *G) {
  619. if (!G->mayBeOverridden()) {
  620. // Redirect direct callers of G to F.
  621. replaceDirectCallers(G, F);
  622. }
  623. // If G was internal then we may have replaced all uses of G with F. If so,
  624. // stop here and delete G. There's no need for a thunk.
  625. if (G->hasLocalLinkage() && G->use_empty()) {
  626. G->eraseFromParent();
  627. return;
  628. }
  629. Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
  630. G->getParent());
  631. BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
  632. IRBuilder<false> Builder(BB);
  633. SmallVector<Value *, 16> Args;
  634. unsigned i = 0;
  635. FunctionType *FFTy = F->getFunctionType();
  636. for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
  637. AI != AE; ++AI) {
  638. Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
  639. ++i;
  640. }
  641. CallInst *CI = Builder.CreateCall(F, Args);
  642. CI->setTailCall();
  643. CI->setCallingConv(F->getCallingConv());
  644. if (NewG->getReturnType()->isVoidTy()) {
  645. Builder.CreateRetVoid();
  646. } else {
  647. Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
  648. }
  649. NewG->copyAttributesFrom(G);
  650. NewG->takeName(G);
  651. removeUsers(G);
  652. G->replaceAllUsesWith(NewG);
  653. G->eraseFromParent();
  654. DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
  655. ++NumThunksWritten;
  656. }
  657. // Replace G with an alias to F and delete G.
  658. void MergeFunctions::writeAlias(Function *F, Function *G) {
  659. Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
  660. GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
  661. BitcastF, G->getParent());
  662. F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
  663. GA->takeName(G);
  664. GA->setVisibility(G->getVisibility());
  665. removeUsers(G);
  666. G->replaceAllUsesWith(GA);
  667. G->eraseFromParent();
  668. DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
  669. ++NumAliasesWritten;
  670. }
  671. // Merge two equivalent functions. Upon completion, Function G is deleted.
  672. void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
  673. if (F->mayBeOverridden()) {
  674. assert(G->mayBeOverridden());
  675. if (HasGlobalAliases) {
  676. // Make them both thunks to the same internal function.
  677. Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
  678. F->getParent());
  679. H->copyAttributesFrom(F);
  680. H->takeName(F);
  681. removeUsers(F);
  682. F->replaceAllUsesWith(H);
  683. unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
  684. writeAlias(F, G);
  685. writeAlias(F, H);
  686. F->setAlignment(MaxAlignment);
  687. F->setLinkage(GlobalValue::PrivateLinkage);
  688. } else {
  689. // We can't merge them. Instead, pick one and update all direct callers
  690. // to call it and hope that we improve the instruction cache hit rate.
  691. replaceDirectCallers(G, F);
  692. }
  693. ++NumDoubleWeak;
  694. } else {
  695. writeThunkOrAlias(F, G);
  696. }
  697. ++NumFunctionsMerged;
  698. }
  699. // Insert a ComparableFunction into the FnSet, or merge it away if equal to one
  700. // that was already inserted.
  701. bool MergeFunctions::insert(ComparableFunction &NewF) {
  702. std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
  703. if (Result.second) {
  704. DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
  705. return false;
  706. }
  707. const ComparableFunction &OldF = *Result.first;
  708. // Don't merge tiny functions, since it can just end up making the function
  709. // larger.
  710. // FIXME: Should still merge them if they are unnamed_addr and produce an
  711. // alias.
  712. if (NewF.getFunc()->size() == 1) {
  713. if (NewF.getFunc()->front().size() <= 2) {
  714. DEBUG(dbgs() << NewF.getFunc()->getName()
  715. << " is to small to bother merging\n");
  716. return false;
  717. }
  718. }
  719. // Never thunk a strong function to a weak function.
  720. assert(!OldF.getFunc()->mayBeOverridden() ||
  721. NewF.getFunc()->mayBeOverridden());
  722. DEBUG(dbgs() << " " << OldF.getFunc()->getName() << " == "
  723. << NewF.getFunc()->getName() << '\n');
  724. Function *DeleteF = NewF.getFunc();
  725. NewF.release();
  726. mergeTwoFunctions(OldF.getFunc(), DeleteF);
  727. return true;
  728. }
  729. // Remove a function from FnSet. If it was already in FnSet, add it to Deferred
  730. // so that we'll look at it in the next round.
  731. void MergeFunctions::remove(Function *F) {
  732. // We need to make sure we remove F, not a function "equal" to F per the
  733. // function equality comparator.
  734. //
  735. // The special "lookup only" ComparableFunction bypasses the expensive
  736. // function comparison in favour of a pointer comparison on the underlying
  737. // Function*'s.
  738. ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
  739. if (FnSet.erase(CF)) {
  740. DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
  741. Deferred.push_back(F);
  742. }
  743. }
  744. // For each instruction used by the value, remove() the function that contains
  745. // the instruction. This should happen right before a call to RAUW.
  746. void MergeFunctions::removeUsers(Value *V) {
  747. std::vector<Value *> Worklist;
  748. Worklist.push_back(V);
  749. while (!Worklist.empty()) {
  750. Value *V = Worklist.back();
  751. Worklist.pop_back();
  752. for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
  753. UI != UE; ++UI) {
  754. Use &U = UI.getUse();
  755. if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
  756. remove(I->getParent()->getParent());
  757. } else if (isa<GlobalValue>(U.getUser())) {
  758. // do nothing
  759. } else if (Constant *C = dyn_cast<Constant>(U.getUser())) {
  760. for (Value::use_iterator CUI = C->use_begin(), CUE = C->use_end();
  761. CUI != CUE; ++CUI)
  762. Worklist.push_back(*CUI);
  763. }
  764. }
  765. }
  766. }