Second patch of patch series that improves MergeFunctions performance time from O...
[oota-llvm.git] / lib / Transforms / IPO / MergeFunctions.cpp
1 //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass looks for equivalent functions that are mergable and folds them.
11 //
12 // A hash is computed from the function, based on its type and number of
13 // basic blocks.
14 //
15 // Once all hashes are computed, we perform an expensive equality comparison
16 // on each function pair. This takes n^2/2 comparisons per bucket, so it's
17 // important that the hash function be high quality. The equality comparison
18 // iterates through each instruction in each basic block.
19 //
20 // When a match is found the functions are folded. 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
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/CallSite.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/InlineAsm.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/LLVMContext.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/Operator.h"
61 #include "llvm/IR/ValueHandle.h"
62 #include "llvm/Pass.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include <vector>
67 using namespace llvm;
68
69 #define DEBUG_TYPE "mergefunc"
70
71 STATISTIC(NumFunctionsMerged, "Number of functions merged");
72 STATISTIC(NumThunksWritten, "Number of thunks generated");
73 STATISTIC(NumAliasesWritten, "Number of aliases generated");
74 STATISTIC(NumDoubleWeak, "Number of new functions created");
75
76 /// Returns the type id for a type to be hashed. We turn pointer types into
77 /// integers here because the actual compare logic below considers pointers and
78 /// integers of the same size as equal.
79 static Type::TypeID getTypeIDForHash(Type *Ty) {
80   if (Ty->isPointerTy())
81     return Type::IntegerTyID;
82   return Ty->getTypeID();
83 }
84
85 /// Creates a hash-code for the function which is the same for any two
86 /// functions that will compare equal, without looking at the instructions
87 /// inside the function.
88 static unsigned profileFunction(const Function *F) {
89   FunctionType *FTy = F->getFunctionType();
90
91   FoldingSetNodeID ID;
92   ID.AddInteger(F->size());
93   ID.AddInteger(F->getCallingConv());
94   ID.AddBoolean(F->hasGC());
95   ID.AddBoolean(FTy->isVarArg());
96   ID.AddInteger(getTypeIDForHash(FTy->getReturnType()));
97   for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
98     ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
99   return ID.ComputeHash();
100 }
101
102 namespace {
103
104 /// ComparableFunction - A struct that pairs together functions with a
105 /// DataLayout so that we can keep them together as elements in the DenseSet.
106 class ComparableFunction {
107 public:
108   static const ComparableFunction EmptyKey;
109   static const ComparableFunction TombstoneKey;
110   static DataLayout * const LookupOnly;
111
112   ComparableFunction(Function *Func, const DataLayout *DL)
113     : Func(Func), Hash(profileFunction(Func)), DL(DL) {}
114
115   Function *getFunc() const { return Func; }
116   unsigned getHash() const { return Hash; }
117   const DataLayout *getDataLayout() const { return DL; }
118
119   // Drops AssertingVH reference to the function. Outside of debug mode, this
120   // does nothing.
121   void release() {
122     assert(Func &&
123            "Attempted to release function twice, or release empty/tombstone!");
124     Func = nullptr;
125   }
126
127 private:
128   explicit ComparableFunction(unsigned Hash)
129     : Func(nullptr), Hash(Hash), DL(nullptr) {}
130
131   AssertingVH<Function> Func;
132   unsigned Hash;
133   const DataLayout *DL;
134 };
135
136 const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
137 const ComparableFunction ComparableFunction::TombstoneKey =
138     ComparableFunction(1);
139 DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
140
141 }
142
143 namespace llvm {
144   template <>
145   struct DenseMapInfo<ComparableFunction> {
146     static ComparableFunction getEmptyKey() {
147       return ComparableFunction::EmptyKey;
148     }
149     static ComparableFunction getTombstoneKey() {
150       return ComparableFunction::TombstoneKey;
151     }
152     static unsigned getHashValue(const ComparableFunction &CF) {
153       return CF.getHash();
154     }
155     static bool isEqual(const ComparableFunction &LHS,
156                         const ComparableFunction &RHS);
157   };
158 }
159
160 namespace {
161
162 /// FunctionComparator - Compares two functions to determine whether or not
163 /// they will generate machine code with the same behaviour. DataLayout is
164 /// used if available. The comparator always fails conservatively (erring on the
165 /// side of claiming that two functions are different).
166 class FunctionComparator {
167 public:
168   FunctionComparator(const DataLayout *DL, const Function *F1,
169                      const Function *F2)
170     : F1(F1), F2(F2), DL(DL) {}
171
172   /// Test whether the two functions have equivalent behaviour.
173   bool compare();
174
175 private:
176   /// Test whether two basic blocks have equivalent behaviour.
177   bool compare(const BasicBlock *BB1, const BasicBlock *BB2);
178
179   /// Constants comparison.
180   /// Its analog to lexicographical comparison between hypothetical numbers
181   /// of next format:
182   /// <bitcastability-trait><raw-bit-contents>
183   ///
184   /// 1. Bitcastability.
185   /// Check whether L's type could be losslessly bitcasted to R's type.
186   /// On this stage method, in case when lossless bitcast is not possible
187   /// method returns -1 or 1, thus also defining which type is greater in
188   /// context of bitcastability.
189   /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
190   ///          to the contents comparison.
191   ///          If types differ, remember types comparison result and check
192   ///          whether we still can bitcast types.
193   /// Stage 1: Types that satisfies isFirstClassType conditions are always
194   ///          greater then others.
195   /// Stage 2: Vector is greater then non-vector.
196   ///          If both types are vectors, then vector with greater bitwidth is
197   ///          greater.
198   ///          If both types are vectors with the same bitwidth, then types
199   ///          are bitcastable, and we can skip other stages, and go to contents
200   ///          comparison.
201   /// Stage 3: Pointer types are greater than non-pointers. If both types are
202   ///          pointers of the same address space - go to contents comparison.
203   ///          Different address spaces: pointer with greater address space is
204   ///          greater.
205   /// Stage 4: Types are neither vectors, nor pointers. And they differ.
206   ///          We don't know how to bitcast them. So, we better don't do it,
207   ///          and return types comparison result (so it determines the
208   ///          relationship among constants we don't know how to bitcast).
209   ///
210   /// Just for clearance, let's see how the set of constants could look
211   /// on single dimension axis:
212   ///
213   /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
214   /// Where: NFCT - Not a FirstClassType
215   ///        FCT - FirstClassTyp:
216   ///
217   /// 2. Compare raw contents.
218   /// It ignores types on this stage and only compares bits from L and R.
219   /// Returns 0, if L and R has equivalent contents.
220   /// -1 or 1 if values are different.
221   /// Pretty trivial:
222   /// 2.1. If contents are numbers, compare numbers.
223   ///    Ints with greater bitwidth are greater. Ints with same bitwidths
224   ///    compared by their contents.
225   /// 2.2. "And so on". Just to avoid discrepancies with comments
226   /// perhaps it would be better to read the implementation itself.
227   /// 3. And again about overall picture. Let's look back at how the ordered set
228   /// of constants will look like:
229   /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
230   ///
231   /// Now look, what could be inside [FCT, "others"], for example:
232   /// [FCT, "others"] =
233   /// [
234   ///   [double 0.1], [double 1.23],
235   ///   [i32 1], [i32 2],
236   ///   { double 1.0 },       ; StructTyID, NumElements = 1
237   ///   { i32 1 },            ; StructTyID, NumElements = 1
238   ///   { double 1, i32 1 },  ; StructTyID, NumElements = 2
239   ///   { i32 1, double 1 }   ; StructTyID, NumElements = 2
240   /// ]
241   ///
242   /// Let's explain the order. Float numbers will be less than integers, just
243   /// because of cmpType terms: FloatTyID < IntegerTyID.
244   /// Floats (with same fltSemantics) are sorted according to their value.
245   /// Then you can see integers, and they are, like a floats,
246   /// could be easy sorted among each others.
247   /// The structures. Structures are grouped at the tail, again because of their
248   /// TypeID: StructTyID > IntegerTyID > FloatTyID.
249   /// Structures with greater number of elements are greater. Structures with
250   /// greater elements going first are greater.
251   /// The same logic with vectors, arrays and other possible complex types.
252   ///
253   /// Bitcastable constants.
254   /// Let's assume, that some constant, belongs to some group of
255   /// "so-called-equal" values with different types, and at the same time
256   /// belongs to another group of constants with equal types
257   /// and "really" equal values.
258   ///
259   /// Now, prove that this is impossible:
260   ///
261   /// If constant A with type TyA is bitcastable to B with type TyB, then:
262   /// 1. All constants with equal types to TyA, are bitcastable to B. Since
263   ///    those should be vectors (if TyA is vector), pointers
264   ///    (if TyA is pointer), or else (if TyA equal to TyB), those types should
265   ///    be equal to TyB.
266   /// 2. All constants with non-equal, but bitcastable types to TyA, are
267   ///    bitcastable to B.
268   ///    Once again, just because we allow it to vectors and pointers only.
269   ///    This statement could be expanded as below:
270   /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
271   ///      vector B, and thus bitcastable to B as well.
272   /// 2.2. All pointers of the same address space, no matter what they point to,
273   ///      bitcastable. So if C is pointer, it could be bitcasted to A and to B.
274   /// So any constant equal or bitcastable to A is equal or bitcastable to B.
275   /// QED.
276   ///
277   /// In another words, for pointers and vectors, we ignore top-level type and
278   /// look at their particular properties (bit-width for vectors, and
279   /// address space for pointers).
280   /// If these properties are equal - compare their contents.
281   int cmpConstants(const Constant *L, const Constant *R);
282
283   /// Assign or look up previously assigned numbers for the two values, and
284   /// return whether the numbers are equal. Numbers are assigned in the order
285   /// visited.
286   bool enumerate(const Value *V1, const Value *V2);
287
288   /// Compare two Instructions for equivalence, similar to
289   /// Instruction::isSameOperationAs but with modifications to the type
290   /// comparison.
291   bool isEquivalentOperation(const Instruction *I1,
292                              const Instruction *I2) const;
293
294   /// Compare two GEPs for equivalent pointer arithmetic.
295   bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
296   bool isEquivalentGEP(const GetElementPtrInst *GEP1,
297                        const GetElementPtrInst *GEP2) {
298     return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
299   }
300
301   /// cmpType - compares two types,
302   /// defines total ordering among the types set.
303   ///
304   /// Return values:
305   /// 0 if types are equal,
306   /// -1 if Left is less than Right,
307   /// +1 if Left is greater than Right.
308   ///
309   /// Description:
310   /// Comparison is broken onto stages. Like in lexicographical comparison
311   /// stage coming first has higher priority.
312   /// On each explanation stage keep in mind total ordering properties.
313   ///
314   /// 0. Before comparison we coerce pointer types of 0 address space to
315   /// integer.
316   /// We also don't bother with same type at left and right, so
317   /// just return 0 in this case.
318   ///
319   /// 1. If types are of different kind (different type IDs).
320   ///    Return result of type IDs comparison, treating them as numbers.
321   /// 2. If types are vectors or integers, compare Type* values as numbers.
322   /// 3. Types has same ID, so check whether they belongs to the next group:
323   /// * Void
324   /// * Float
325   /// * Double
326   /// * X86_FP80
327   /// * FP128
328   /// * PPC_FP128
329   /// * Label
330   /// * Metadata
331   /// If so - return 0, yes - we can treat these types as equal only because
332   /// their IDs are same.
333   /// 4. If Left and Right are pointers, return result of address space
334   /// comparison (numbers comparison). We can treat pointer types of same
335   /// address space as equal.
336   /// 5. If types are complex.
337   /// Then both Left and Right are to be expanded and their element types will
338   /// be checked with the same way. If we get Res != 0 on some stage, return it.
339   /// Otherwise return 0.
340   /// 6. For all other cases put llvm_unreachable.
341   int cmpType(Type *TyL, Type *TyR) const;
342
343   bool isEquivalentType(Type *Ty1, Type *Ty2) const {
344     return cmpType(Ty1, Ty2) == 0;
345   }
346
347   int cmpNumbers(uint64_t L, uint64_t R) const;
348
349   int cmpAPInt(const APInt &L, const APInt &R) const;
350   int cmpAPFloat(const APFloat &L, const APFloat &R) const;
351
352   // The two functions undergoing comparison.
353   const Function *F1, *F2;
354
355   const DataLayout *DL;
356
357   DenseMap<const Value *, const Value *> id_map;
358   DenseSet<const Value *> seen_values;
359 };
360
361 }
362
363 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
364   if (L < R) return -1;
365   if (L > R) return 1;
366   return 0;
367 }
368
369 int FunctionComparator::cmpAPInt(const APInt &L, const APInt &R) const {
370   if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
371     return Res;
372   if (L.ugt(R)) return 1;
373   if (R.ugt(L)) return -1;
374   return 0;
375 }
376
377 int FunctionComparator::cmpAPFloat(const APFloat &L, const APFloat &R) const {
378   if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
379                            (uint64_t)&R.getSemantics()))
380     return Res;
381   return cmpAPInt(L.bitcastToAPInt(), R.bitcastToAPInt());
382 }
383
384 /// Constants comparison:
385 /// 1. Check whether type of L constant could be losslessly bitcasted to R
386 /// type.
387 /// 2. Compare constant contents.
388 /// For more details see declaration comments.
389 int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
390
391   Type *TyL = L->getType();
392   Type *TyR = R->getType();
393
394   // Check whether types are bitcastable. This part is just re-factored
395   // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
396   // we also pack into result which type is "less" for us.
397   int TypesRes = cmpType(TyL, TyR);
398   if (TypesRes != 0) {
399     // Types are different, but check whether we can bitcast them.
400     if (!TyL->isFirstClassType()) {
401       if (TyR->isFirstClassType())
402         return -1;
403       // Neither TyL nor TyR are values of first class type. Return the result
404       // of comparing the types
405       return TypesRes;
406     }
407     if (!TyR->isFirstClassType()) {
408       if (TyL->isFirstClassType())
409         return 1;
410       return TypesRes;
411     }
412
413     // Vector -> Vector conversions are always lossless if the two vector types
414     // have the same size, otherwise not.
415     unsigned TyLWidth = 0;
416     unsigned TyRWidth = 0;
417
418     if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
419       TyLWidth = VecTyL->getBitWidth();
420     if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
421       TyRWidth = VecTyR->getBitWidth();
422
423     if (TyLWidth != TyRWidth)
424       return cmpNumbers(TyLWidth, TyRWidth);
425
426     // Zero bit-width means neither TyL nor TyR are vectors.
427     if (!TyLWidth) {
428       PointerType *PTyL = dyn_cast<PointerType>(TyL);
429       PointerType *PTyR = dyn_cast<PointerType>(TyR);
430       if (PTyL && PTyR) {
431         unsigned AddrSpaceL = PTyL->getAddressSpace();
432         unsigned AddrSpaceR = PTyR->getAddressSpace();
433         if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
434           return Res;
435       }
436       if (PTyL)
437         return 1;
438       if (PTyR)
439         return -1;
440
441       // TyL and TyR aren't vectors, nor pointers. We don't know how to
442       // bitcast them.
443       return TypesRes;
444     }
445   }
446
447   // OK, types are bitcastable, now check constant contents.
448
449   if (L->isNullValue() && R->isNullValue())
450     return TypesRes;
451   if (L->isNullValue() && !R->isNullValue())
452     return 1;
453   if (!L->isNullValue() && R->isNullValue())
454     return -1;
455
456   if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
457     return Res;
458
459   switch (L->getValueID()) {
460   case Value::UndefValueVal: return TypesRes;
461   case Value::ConstantIntVal: {
462     const APInt &LInt = cast<ConstantInt>(L)->getValue();
463     const APInt &RInt = cast<ConstantInt>(R)->getValue();
464     return cmpAPInt(LInt, RInt);
465   }
466   case Value::ConstantFPVal: {
467     const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
468     const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
469     return cmpAPFloat(LAPF, RAPF);
470   }
471   case Value::ConstantArrayVal: {
472     const ConstantArray *LA = cast<ConstantArray>(L);
473     const ConstantArray *RA = cast<ConstantArray>(R);
474     uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
475     uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
476     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
477       return Res;
478     for (uint64_t i = 0; i < NumElementsL; ++i) {
479       if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
480                                  cast<Constant>(RA->getOperand(i))))
481         return Res;
482     }
483     return 0;
484   }
485   case Value::ConstantStructVal: {
486     const ConstantStruct *LS = cast<ConstantStruct>(L);
487     const ConstantStruct *RS = cast<ConstantStruct>(R);
488     unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
489     unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
490     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
491       return Res;
492     for (unsigned i = 0; i != NumElementsL; ++i) {
493       if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
494                                  cast<Constant>(RS->getOperand(i))))
495         return Res;
496     }
497     return 0;
498   }
499   case Value::ConstantVectorVal: {
500     const ConstantVector *LV = cast<ConstantVector>(L);
501     const ConstantVector *RV = cast<ConstantVector>(R);
502     unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
503     unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
504     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
505       return Res;
506     for (uint64_t i = 0; i < NumElementsL; ++i) {
507       if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
508                                  cast<Constant>(RV->getOperand(i))))
509         return Res;
510     }
511     return 0;
512   }
513   case Value::ConstantExprVal: {
514     const ConstantExpr *LE = cast<ConstantExpr>(L);
515     const ConstantExpr *RE = cast<ConstantExpr>(R);
516     unsigned NumOperandsL = LE->getNumOperands();
517     unsigned NumOperandsR = RE->getNumOperands();
518     if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
519       return Res;
520     for (unsigned i = 0; i < NumOperandsL; ++i) {
521       if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
522                                  cast<Constant>(RE->getOperand(i))))
523         return Res;
524     }
525     return 0;
526   }
527   case Value::FunctionVal:
528   case Value::GlobalVariableVal:
529   case Value::GlobalAliasVal:
530   default: // Unknown constant, cast L and R pointers to numbers and compare.
531     return cmpNumbers((uint64_t)L, (uint64_t)R);
532   }
533 }
534
535 /// cmpType - compares two types,
536 /// defines total ordering among the types set.
537 /// See method declaration comments for more details.
538 int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
539
540   PointerType *PTyL = dyn_cast<PointerType>(TyL);
541   PointerType *PTyR = dyn_cast<PointerType>(TyR);
542
543   if (DL) {
544     if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
545     if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
546   }
547
548   if (TyL == TyR)
549     return 0;
550
551   if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
552     return Res;
553
554   switch (TyL->getTypeID()) {
555   default:
556     llvm_unreachable("Unknown type!");
557     // Fall through in Release mode.
558   case Type::IntegerTyID:
559   case Type::VectorTyID:
560     // TyL == TyR would have returned true earlier.
561     return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
562
563   case Type::VoidTyID:
564   case Type::FloatTyID:
565   case Type::DoubleTyID:
566   case Type::X86_FP80TyID:
567   case Type::FP128TyID:
568   case Type::PPC_FP128TyID:
569   case Type::LabelTyID:
570   case Type::MetadataTyID:
571     return 0;
572
573   case Type::PointerTyID: {
574     assert(PTyL && PTyR && "Both types must be pointers here.");
575     return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
576   }
577
578   case Type::StructTyID: {
579     StructType *STyL = cast<StructType>(TyL);
580     StructType *STyR = cast<StructType>(TyR);
581     if (STyL->getNumElements() != STyR->getNumElements())
582       return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
583
584     if (STyL->isPacked() != STyR->isPacked())
585       return cmpNumbers(STyL->isPacked(), STyR->isPacked());
586
587     for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
588       if (int Res = cmpType(STyL->getElementType(i),
589                             STyR->getElementType(i)))
590         return Res;
591     }
592     return 0;
593   }
594
595   case Type::FunctionTyID: {
596     FunctionType *FTyL = cast<FunctionType>(TyL);
597     FunctionType *FTyR = cast<FunctionType>(TyR);
598     if (FTyL->getNumParams() != FTyR->getNumParams())
599       return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
600
601     if (FTyL->isVarArg() != FTyR->isVarArg())
602       return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
603
604     if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
605       return Res;
606
607     for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
608       if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
609         return Res;
610     }
611     return 0;
612   }
613
614   case Type::ArrayTyID: {
615     ArrayType *ATyL = cast<ArrayType>(TyL);
616     ArrayType *ATyR = cast<ArrayType>(TyR);
617     if (ATyL->getNumElements() != ATyR->getNumElements())
618       return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
619     return cmpType(ATyL->getElementType(), ATyR->getElementType());
620   }
621   }
622 }
623
624 // Determine whether the two operations are the same except that pointer-to-A
625 // and pointer-to-B are equivalent. This should be kept in sync with
626 // Instruction::isSameOperationAs.
627 bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
628                                                const Instruction *I2) const {
629   // Differences from Instruction::isSameOperationAs:
630   //  * replace type comparison with calls to isEquivalentType.
631   //  * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
632   //  * because of the above, we don't test for the tail bit on calls later on
633   if (I1->getOpcode() != I2->getOpcode() ||
634       I1->getNumOperands() != I2->getNumOperands() ||
635       !isEquivalentType(I1->getType(), I2->getType()) ||
636       !I1->hasSameSubclassOptionalData(I2))
637     return false;
638
639   // We have two instructions of identical opcode and #operands.  Check to see
640   // if all operands are the same type
641   for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
642     if (!isEquivalentType(I1->getOperand(i)->getType(),
643                           I2->getOperand(i)->getType()))
644       return false;
645
646   // Check special state that is a part of some instructions.
647   if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
648     return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
649            LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() &&
650            LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
651            LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
652   if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
653     return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
654            SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() &&
655            SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
656            SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
657   if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
658     return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
659   if (const CallInst *CI = dyn_cast<CallInst>(I1))
660     return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
661            CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
662   if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
663     return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
664            CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes();
665   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
666     return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
667   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
668     return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
669   if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
670     return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
671            FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
672   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
673     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
674            CXI->getSuccessOrdering() ==
675                cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
676            CXI->getFailureOrdering() ==
677                cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
678            CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
679   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
680     return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
681            RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
682            RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
683            RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
684
685   return true;
686 }
687
688 // Determine whether two GEP operations perform the same underlying arithmetic.
689 bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
690                                          const GEPOperator *GEP2) {
691   unsigned AS = GEP1->getPointerAddressSpace();
692   if (AS != GEP2->getPointerAddressSpace())
693     return false;
694
695   if (DL) {
696     // When we have target data, we can reduce the GEP down to the value in bytes
697     // added to the address.
698     unsigned BitWidth = DL ? DL->getPointerSizeInBits(AS) : 1;
699     APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0);
700     if (GEP1->accumulateConstantOffset(*DL, Offset1) &&
701         GEP2->accumulateConstantOffset(*DL, Offset2)) {
702       return Offset1 == Offset2;
703     }
704   }
705
706   if (GEP1->getPointerOperand()->getType() !=
707       GEP2->getPointerOperand()->getType())
708     return false;
709
710   if (GEP1->getNumOperands() != GEP2->getNumOperands())
711     return false;
712
713   for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
714     if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
715       return false;
716   }
717
718   return true;
719 }
720
721 // Compare two values used by the two functions under pair-wise comparison. If
722 // this is the first time the values are seen, they're added to the mapping so
723 // that we will detect mismatches on next use.
724 bool FunctionComparator::enumerate(const Value *V1, const Value *V2) {
725   // Check for function @f1 referring to itself and function @f2 referring to
726   // itself, or referring to each other, or both referring to either of them.
727   // They're all equivalent if the two functions are otherwise equivalent.
728   if (V1 == F1 && V2 == F2)
729     return true;
730   if (V1 == F2 && V2 == F1)
731     return true;
732
733   if (const Constant *C1 = dyn_cast<Constant>(V1)) {
734     if (V1 == V2) return true;
735     const Constant *C2 = dyn_cast<Constant>(V2);
736     if (!C2) return false;
737     // TODO: constant expressions with GEP or references to F1 or F2.
738     if (C1->isNullValue() && C2->isNullValue() &&
739         isEquivalentType(C1->getType(), C2->getType()))
740       return true;
741
742     // Compare constants:
743     // Check whether type of C1 is bitcastable to C2's type.
744     // If the bitcast is possible then compare raw constants contents.
745     return cmpConstants(C1, C2) == 0;
746   }
747
748   if (isa<InlineAsm>(V1) || isa<InlineAsm>(V2))
749     return V1 == V2;
750
751   // Check that V1 maps to V2. If we find a value that V1 maps to then we simply
752   // check whether it's equal to V2. When there is no mapping then we need to
753   // ensure that V2 isn't already equivalent to something else. For this
754   // purpose, we track the V2 values in a set.
755
756   const Value *&map_elem = id_map[V1];
757   if (map_elem)
758     return map_elem == V2;
759   if (!seen_values.insert(V2).second)
760     return false;
761   map_elem = V2;
762   return true;
763 }
764
765 // Test whether two basic blocks have equivalent behaviour.
766 bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) {
767   BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
768   BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
769
770   do {
771     if (!enumerate(F1I, F2I))
772       return false;
773
774     if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
775       const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
776       if (!GEP2)
777         return false;
778
779       if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
780         return false;
781
782       if (!isEquivalentGEP(GEP1, GEP2))
783         return false;
784     } else {
785       if (!isEquivalentOperation(F1I, F2I))
786         return false;
787
788       assert(F1I->getNumOperands() == F2I->getNumOperands());
789       for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
790         Value *OpF1 = F1I->getOperand(i);
791         Value *OpF2 = F2I->getOperand(i);
792
793         if (!enumerate(OpF1, OpF2))
794           return false;
795
796         if (OpF1->getValueID() != OpF2->getValueID() ||
797             !isEquivalentType(OpF1->getType(), OpF2->getType()))
798           return false;
799       }
800     }
801
802     ++F1I, ++F2I;
803   } while (F1I != F1E && F2I != F2E);
804
805   return F1I == F1E && F2I == F2E;
806 }
807
808 // Test whether the two functions have equivalent behaviour.
809 bool FunctionComparator::compare() {
810   // We need to recheck everything, but check the things that weren't included
811   // in the hash first.
812
813   if (F1->getAttributes() != F2->getAttributes())
814     return false;
815
816   if (F1->hasGC() != F2->hasGC())
817     return false;
818
819   if (F1->hasGC() && F1->getGC() != F2->getGC())
820     return false;
821
822   if (F1->hasSection() != F2->hasSection())
823     return false;
824
825   if (F1->hasSection() && F1->getSection() != F2->getSection())
826     return false;
827
828   if (F1->isVarArg() != F2->isVarArg())
829     return false;
830
831   // TODO: if it's internal and only used in direct calls, we could handle this
832   // case too.
833   if (F1->getCallingConv() != F2->getCallingConv())
834     return false;
835
836   if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
837     return false;
838
839   assert(F1->arg_size() == F2->arg_size() &&
840          "Identically typed functions have different numbers of args!");
841
842   // Visit the arguments so that they get enumerated in the order they're
843   // passed in.
844   for (Function::const_arg_iterator f1i = F1->arg_begin(),
845          f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
846     if (!enumerate(f1i, f2i))
847       llvm_unreachable("Arguments repeat!");
848   }
849
850   // We do a CFG-ordered walk since the actual ordering of the blocks in the
851   // linked list is immaterial. Our walk starts at the entry block for both
852   // functions, then takes each block from each terminator in order. As an
853   // artifact, this also means that unreachable blocks are ignored.
854   SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
855   SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
856
857   F1BBs.push_back(&F1->getEntryBlock());
858   F2BBs.push_back(&F2->getEntryBlock());
859
860   VisitedBBs.insert(F1BBs[0]);
861   while (!F1BBs.empty()) {
862     const BasicBlock *F1BB = F1BBs.pop_back_val();
863     const BasicBlock *F2BB = F2BBs.pop_back_val();
864
865     if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB))
866       return false;
867
868     const TerminatorInst *F1TI = F1BB->getTerminator();
869     const TerminatorInst *F2TI = F2BB->getTerminator();
870
871     assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
872     for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
873       if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
874         continue;
875
876       F1BBs.push_back(F1TI->getSuccessor(i));
877       F2BBs.push_back(F2TI->getSuccessor(i));
878     }
879   }
880   return true;
881 }
882
883 namespace {
884
885 /// MergeFunctions finds functions which will generate identical machine code,
886 /// by considering all pointer types to be equivalent. Once identified,
887 /// MergeFunctions will fold them by replacing a call to one to a call to a
888 /// bitcast of the other.
889 ///
890 class MergeFunctions : public ModulePass {
891 public:
892   static char ID;
893   MergeFunctions()
894     : ModulePass(ID), HasGlobalAliases(false) {
895     initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
896   }
897
898   bool runOnModule(Module &M) override;
899
900 private:
901   typedef DenseSet<ComparableFunction> FnSetType;
902
903   /// A work queue of functions that may have been modified and should be
904   /// analyzed again.
905   std::vector<WeakVH> Deferred;
906
907   /// Insert a ComparableFunction into the FnSet, or merge it away if it's
908   /// equal to one that's already present.
909   bool insert(ComparableFunction &NewF);
910
911   /// Remove a Function from the FnSet and queue it up for a second sweep of
912   /// analysis.
913   void remove(Function *F);
914
915   /// Find the functions that use this Value and remove them from FnSet and
916   /// queue the functions.
917   void removeUsers(Value *V);
918
919   /// Replace all direct calls of Old with calls of New. Will bitcast New if
920   /// necessary to make types match.
921   void replaceDirectCallers(Function *Old, Function *New);
922
923   /// Merge two equivalent functions. Upon completion, G may be deleted, or may
924   /// be converted into a thunk. In either case, it should never be visited
925   /// again.
926   void mergeTwoFunctions(Function *F, Function *G);
927
928   /// Replace G with a thunk or an alias to F. Deletes G.
929   void writeThunkOrAlias(Function *F, Function *G);
930
931   /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
932   /// of G with bitcast(F). Deletes G.
933   void writeThunk(Function *F, Function *G);
934
935   /// Replace G with an alias to F. Deletes G.
936   void writeAlias(Function *F, Function *G);
937
938   /// The set of all distinct functions. Use the insert() and remove() methods
939   /// to modify it.
940   FnSetType FnSet;
941
942   /// DataLayout for more accurate GEP comparisons. May be NULL.
943   const DataLayout *DL;
944
945   /// Whether or not the target supports global aliases.
946   bool HasGlobalAliases;
947 };
948
949 }  // end anonymous namespace
950
951 char MergeFunctions::ID = 0;
952 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
953
954 ModulePass *llvm::createMergeFunctionsPass() {
955   return new MergeFunctions();
956 }
957
958 bool MergeFunctions::runOnModule(Module &M) {
959   bool Changed = false;
960   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
961   DL = DLP ? &DLP->getDataLayout() : nullptr;
962
963   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
964     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
965       Deferred.push_back(WeakVH(I));
966   }
967   FnSet.resize(Deferred.size());
968
969   do {
970     std::vector<WeakVH> Worklist;
971     Deferred.swap(Worklist);
972
973     DEBUG(dbgs() << "size of module: " << M.size() << '\n');
974     DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
975
976     // Insert only strong functions and merge them. Strong function merging
977     // always deletes one of them.
978     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
979            E = Worklist.end(); I != E; ++I) {
980       if (!*I) continue;
981       Function *F = cast<Function>(*I);
982       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
983           !F->mayBeOverridden()) {
984         ComparableFunction CF = ComparableFunction(F, DL);
985         Changed |= insert(CF);
986       }
987     }
988
989     // Insert only weak functions and merge them. By doing these second we
990     // create thunks to the strong function when possible. When two weak
991     // functions are identical, we create a new strong function with two weak
992     // weak thunks to it which are identical but not mergable.
993     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
994            E = Worklist.end(); I != E; ++I) {
995       if (!*I) continue;
996       Function *F = cast<Function>(*I);
997       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
998           F->mayBeOverridden()) {
999         ComparableFunction CF = ComparableFunction(F, DL);
1000         Changed |= insert(CF);
1001       }
1002     }
1003     DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
1004   } while (!Deferred.empty());
1005
1006   FnSet.clear();
1007
1008   return Changed;
1009 }
1010
1011 bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
1012                                                const ComparableFunction &RHS) {
1013   if (LHS.getFunc() == RHS.getFunc() &&
1014       LHS.getHash() == RHS.getHash())
1015     return true;
1016   if (!LHS.getFunc() || !RHS.getFunc())
1017     return false;
1018
1019   // One of these is a special "underlying pointer comparison only" object.
1020   if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
1021       RHS.getDataLayout() == ComparableFunction::LookupOnly)
1022     return false;
1023
1024   assert(LHS.getDataLayout() == RHS.getDataLayout() &&
1025          "Comparing functions for different targets");
1026
1027   return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(),
1028                             RHS.getFunc()).compare();
1029 }
1030
1031 // Replace direct callers of Old with New.
1032 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1033   Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
1034   for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1035     Use *U = &*UI;
1036     ++UI;
1037     CallSite CS(U->getUser());
1038     if (CS && CS.isCallee(U)) {
1039       remove(CS.getInstruction()->getParent()->getParent());
1040       U->set(BitcastNew);
1041     }
1042   }
1043 }
1044
1045 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1046 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
1047   if (HasGlobalAliases && G->hasUnnamedAddr()) {
1048     if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1049         G->hasWeakLinkage()) {
1050       writeAlias(F, G);
1051       return;
1052     }
1053   }
1054
1055   writeThunk(F, G);
1056 }
1057
1058 // Helper for writeThunk,
1059 // Selects proper bitcast operation,
1060 // but a bit simpler then CastInst::getCastOpcode.
1061 static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
1062   Type *SrcTy = V->getType();
1063   if (SrcTy->isStructTy()) {
1064     assert(DestTy->isStructTy());
1065     assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1066     Value *Result = UndefValue::get(DestTy);
1067     for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1068       Value *Element = createCast(
1069           Builder, Builder.CreateExtractValue(V, ArrayRef<unsigned int>(I)),
1070           DestTy->getStructElementType(I));
1071
1072       Result =
1073           Builder.CreateInsertValue(Result, Element, ArrayRef<unsigned int>(I));
1074     }
1075     return Result;
1076   }
1077   assert(!DestTy->isStructTy());
1078   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1079     return Builder.CreateIntToPtr(V, DestTy);
1080   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1081     return Builder.CreatePtrToInt(V, DestTy);
1082   else
1083     return Builder.CreateBitCast(V, DestTy);
1084 }
1085
1086 // Replace G with a simple tail call to bitcast(F). Also replace direct uses
1087 // of G with bitcast(F). Deletes G.
1088 void MergeFunctions::writeThunk(Function *F, Function *G) {
1089   if (!G->mayBeOverridden()) {
1090     // Redirect direct callers of G to F.
1091     replaceDirectCallers(G, F);
1092   }
1093
1094   // If G was internal then we may have replaced all uses of G with F. If so,
1095   // stop here and delete G. There's no need for a thunk.
1096   if (G->hasLocalLinkage() && G->use_empty()) {
1097     G->eraseFromParent();
1098     return;
1099   }
1100
1101   Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1102                                     G->getParent());
1103   BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
1104   IRBuilder<false> Builder(BB);
1105
1106   SmallVector<Value *, 16> Args;
1107   unsigned i = 0;
1108   FunctionType *FFTy = F->getFunctionType();
1109   for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1110        AI != AE; ++AI) {
1111     Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
1112     ++i;
1113   }
1114
1115   CallInst *CI = Builder.CreateCall(F, Args);
1116   CI->setTailCall();
1117   CI->setCallingConv(F->getCallingConv());
1118   if (NewG->getReturnType()->isVoidTy()) {
1119     Builder.CreateRetVoid();
1120   } else {
1121     Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
1122   }
1123
1124   NewG->copyAttributesFrom(G);
1125   NewG->takeName(G);
1126   removeUsers(G);
1127   G->replaceAllUsesWith(NewG);
1128   G->eraseFromParent();
1129
1130   DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
1131   ++NumThunksWritten;
1132 }
1133
1134 // Replace G with an alias to F and delete G.
1135 void MergeFunctions::writeAlias(Function *F, Function *G) {
1136   Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
1137   GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
1138                                     BitcastF, G->getParent());
1139   F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1140   GA->takeName(G);
1141   GA->setVisibility(G->getVisibility());
1142   removeUsers(G);
1143   G->replaceAllUsesWith(GA);
1144   G->eraseFromParent();
1145
1146   DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
1147   ++NumAliasesWritten;
1148 }
1149
1150 // Merge two equivalent functions. Upon completion, Function G is deleted.
1151 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
1152   if (F->mayBeOverridden()) {
1153     assert(G->mayBeOverridden());
1154
1155     if (HasGlobalAliases) {
1156       // Make them both thunks to the same internal function.
1157       Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1158                                      F->getParent());
1159       H->copyAttributesFrom(F);
1160       H->takeName(F);
1161       removeUsers(F);
1162       F->replaceAllUsesWith(H);
1163
1164       unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1165
1166       writeAlias(F, G);
1167       writeAlias(F, H);
1168
1169       F->setAlignment(MaxAlignment);
1170       F->setLinkage(GlobalValue::PrivateLinkage);
1171     } else {
1172       // We can't merge them. Instead, pick one and update all direct callers
1173       // to call it and hope that we improve the instruction cache hit rate.
1174       replaceDirectCallers(G, F);
1175     }
1176
1177     ++NumDoubleWeak;
1178   } else {
1179     writeThunkOrAlias(F, G);
1180   }
1181
1182   ++NumFunctionsMerged;
1183 }
1184
1185 // Insert a ComparableFunction into the FnSet, or merge it away if equal to one
1186 // that was already inserted.
1187 bool MergeFunctions::insert(ComparableFunction &NewF) {
1188   std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
1189   if (Result.second) {
1190     DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
1191     return false;
1192   }
1193
1194   const ComparableFunction &OldF = *Result.first;
1195
1196   // Don't merge tiny functions, since it can just end up making the function
1197   // larger.
1198   // FIXME: Should still merge them if they are unnamed_addr and produce an
1199   // alias.
1200   if (NewF.getFunc()->size() == 1) {
1201     if (NewF.getFunc()->front().size() <= 2) {
1202       DEBUG(dbgs() << NewF.getFunc()->getName()
1203             << " is to small to bother merging\n");
1204       return false;
1205     }
1206   }
1207
1208   // Never thunk a strong function to a weak function.
1209   assert(!OldF.getFunc()->mayBeOverridden() ||
1210          NewF.getFunc()->mayBeOverridden());
1211
1212   DEBUG(dbgs() << "  " << OldF.getFunc()->getName() << " == "
1213                << NewF.getFunc()->getName() << '\n');
1214
1215   Function *DeleteF = NewF.getFunc();
1216   NewF.release();
1217   mergeTwoFunctions(OldF.getFunc(), DeleteF);
1218   return true;
1219 }
1220
1221 // Remove a function from FnSet. If it was already in FnSet, add it to Deferred
1222 // so that we'll look at it in the next round.
1223 void MergeFunctions::remove(Function *F) {
1224   // We need to make sure we remove F, not a function "equal" to F per the
1225   // function equality comparator.
1226   //
1227   // The special "lookup only" ComparableFunction bypasses the expensive
1228   // function comparison in favour of a pointer comparison on the underlying
1229   // Function*'s.
1230   ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
1231   if (FnSet.erase(CF)) {
1232     DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
1233     Deferred.push_back(F);
1234   }
1235 }
1236
1237 // For each instruction used by the value, remove() the function that contains
1238 // the instruction. This should happen right before a call to RAUW.
1239 void MergeFunctions::removeUsers(Value *V) {
1240   std::vector<Value *> Worklist;
1241   Worklist.push_back(V);
1242   while (!Worklist.empty()) {
1243     Value *V = Worklist.back();
1244     Worklist.pop_back();
1245
1246     for (User *U : V->users()) {
1247       if (Instruction *I = dyn_cast<Instruction>(U)) {
1248         remove(I->getParent()->getParent());
1249       } else if (isa<GlobalValue>(U)) {
1250         // do nothing
1251       } else if (Constant *C = dyn_cast<Constant>(U)) {
1252         for (User *UU : C->users())
1253           Worklist.push_back(UU);
1254       }
1255     }
1256   }
1257 }