MergeFunctions Pass, introduced total ordering among values.
[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   /// Comparison order:
287   /// Stage 0: Value that is function itself is always greater then others.
288   ///          If left and right values are references to their functions, then
289   ///          they are equal.
290   /// Stage 1: Constants are greater than non-constants.
291   ///          If both left and right are constants, then the result of
292   ///          cmpConstants is used as cmpValues result.
293   /// Stage 2: InlineAsm instances are greater than others. If both left and
294   ///          right are InlineAsm instances, InlineAsm* pointers casted to
295   ///          integers and compared as numbers.
296   /// Stage 3: For all other cases we compare order we meet these values in
297   ///          their functions. If right value was met first during scanning,
298   ///          then left value is greater.
299   ///          In another words, we compare serial numbers, for more details
300   ///          see comments for sn_mapL and sn_mapR.
301   int cmpValues(const Value *L, const Value *R);
302
303   bool enumerate(const Value *V1, const Value *V2) {
304     return cmpValues(V1, V2) == 0;
305   }
306
307   /// Compare two Instructions for equivalence, similar to
308   /// Instruction::isSameOperationAs but with modifications to the type
309   /// comparison.
310   bool isEquivalentOperation(const Instruction *I1,
311                              const Instruction *I2) const;
312
313   /// Compare two GEPs for equivalent pointer arithmetic.
314   bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2);
315   bool isEquivalentGEP(const GetElementPtrInst *GEP1,
316                        const GetElementPtrInst *GEP2) {
317     return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
318   }
319
320   /// cmpType - compares two types,
321   /// defines total ordering among the types set.
322   ///
323   /// Return values:
324   /// 0 if types are equal,
325   /// -1 if Left is less than Right,
326   /// +1 if Left is greater than Right.
327   ///
328   /// Description:
329   /// Comparison is broken onto stages. Like in lexicographical comparison
330   /// stage coming first has higher priority.
331   /// On each explanation stage keep in mind total ordering properties.
332   ///
333   /// 0. Before comparison we coerce pointer types of 0 address space to
334   /// integer.
335   /// We also don't bother with same type at left and right, so
336   /// just return 0 in this case.
337   ///
338   /// 1. If types are of different kind (different type IDs).
339   ///    Return result of type IDs comparison, treating them as numbers.
340   /// 2. If types are vectors or integers, compare Type* values as numbers.
341   /// 3. Types has same ID, so check whether they belongs to the next group:
342   /// * Void
343   /// * Float
344   /// * Double
345   /// * X86_FP80
346   /// * FP128
347   /// * PPC_FP128
348   /// * Label
349   /// * Metadata
350   /// If so - return 0, yes - we can treat these types as equal only because
351   /// their IDs are same.
352   /// 4. If Left and Right are pointers, return result of address space
353   /// comparison (numbers comparison). We can treat pointer types of same
354   /// address space as equal.
355   /// 5. If types are complex.
356   /// Then both Left and Right are to be expanded and their element types will
357   /// be checked with the same way. If we get Res != 0 on some stage, return it.
358   /// Otherwise return 0.
359   /// 6. For all other cases put llvm_unreachable.
360   int cmpType(Type *TyL, Type *TyR) const;
361
362   bool isEquivalentType(Type *Ty1, Type *Ty2) const {
363     return cmpType(Ty1, Ty2) == 0;
364   }
365
366   int cmpNumbers(uint64_t L, uint64_t R) const;
367
368   int cmpAPInt(const APInt &L, const APInt &R) const;
369   int cmpAPFloat(const APFloat &L, const APFloat &R) const;
370
371   // The two functions undergoing comparison.
372   const Function *F1, *F2;
373
374   const DataLayout *DL;
375
376   /// Assign serial numbers to values from left function, and values from
377   /// right function.
378   /// Explanation:
379   /// Being comparing functions we need to compare values we meet at left and
380   /// right sides.
381   /// Its easy to sort things out for external values. It just should be
382   /// the same value at left and right.
383   /// But for local values (those were introduced inside function body)
384   /// we have to ensure they were introduced at exactly the same place,
385   /// and plays the same role.
386   /// Let's assign serial number to each value when we meet it first time.
387   /// Values that were met at same place will be with same serial numbers.
388   /// In this case it would be good to explain few points about values assigned
389   /// to BBs and other ways of implementation (see below).
390   ///
391   /// 1. Safety of BB reordering.
392   /// It's safe to change the order of BasicBlocks in function.
393   /// Relationship with other functions and serial numbering will not be
394   /// changed in this case.
395   /// As follows from FunctionComparator::compare(), we do CFG walk: we start
396   /// from the entry, and then take each terminator. So it doesn't matter how in
397   /// fact BBs are ordered in function. And since cmpValues are called during
398   /// this walk, the numbering depends only on how BBs located inside the CFG.
399   /// So the answer is - yes. We will get the same numbering.
400   ///
401   /// 2. Impossibility to use dominance properties of values.
402   /// If we compare two instruction operands: first is usage of local
403   /// variable AL from function FL, and second is usage of local variable AR
404   /// from FR, we could compare their origins and check whether they are
405   /// defined at the same place.
406   /// But, we are still not able to compare operands of PHI nodes, since those
407   /// could be operands from further BBs we didn't scan yet.
408   /// So it's impossible to use dominance properties in general.
409   DenseMap<const Value*, int> sn_mapL, sn_mapR;
410 };
411
412 }
413
414 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
415   if (L < R) return -1;
416   if (L > R) return 1;
417   return 0;
418 }
419
420 int FunctionComparator::cmpAPInt(const APInt &L, const APInt &R) const {
421   if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
422     return Res;
423   if (L.ugt(R)) return 1;
424   if (R.ugt(L)) return -1;
425   return 0;
426 }
427
428 int FunctionComparator::cmpAPFloat(const APFloat &L, const APFloat &R) const {
429   if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
430                            (uint64_t)&R.getSemantics()))
431     return Res;
432   return cmpAPInt(L.bitcastToAPInt(), R.bitcastToAPInt());
433 }
434
435 /// Constants comparison:
436 /// 1. Check whether type of L constant could be losslessly bitcasted to R
437 /// type.
438 /// 2. Compare constant contents.
439 /// For more details see declaration comments.
440 int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
441
442   Type *TyL = L->getType();
443   Type *TyR = R->getType();
444
445   // Check whether types are bitcastable. This part is just re-factored
446   // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
447   // we also pack into result which type is "less" for us.
448   int TypesRes = cmpType(TyL, TyR);
449   if (TypesRes != 0) {
450     // Types are different, but check whether we can bitcast them.
451     if (!TyL->isFirstClassType()) {
452       if (TyR->isFirstClassType())
453         return -1;
454       // Neither TyL nor TyR are values of first class type. Return the result
455       // of comparing the types
456       return TypesRes;
457     }
458     if (!TyR->isFirstClassType()) {
459       if (TyL->isFirstClassType())
460         return 1;
461       return TypesRes;
462     }
463
464     // Vector -> Vector conversions are always lossless if the two vector types
465     // have the same size, otherwise not.
466     unsigned TyLWidth = 0;
467     unsigned TyRWidth = 0;
468
469     if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
470       TyLWidth = VecTyL->getBitWidth();
471     if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
472       TyRWidth = VecTyR->getBitWidth();
473
474     if (TyLWidth != TyRWidth)
475       return cmpNumbers(TyLWidth, TyRWidth);
476
477     // Zero bit-width means neither TyL nor TyR are vectors.
478     if (!TyLWidth) {
479       PointerType *PTyL = dyn_cast<PointerType>(TyL);
480       PointerType *PTyR = dyn_cast<PointerType>(TyR);
481       if (PTyL && PTyR) {
482         unsigned AddrSpaceL = PTyL->getAddressSpace();
483         unsigned AddrSpaceR = PTyR->getAddressSpace();
484         if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
485           return Res;
486       }
487       if (PTyL)
488         return 1;
489       if (PTyR)
490         return -1;
491
492       // TyL and TyR aren't vectors, nor pointers. We don't know how to
493       // bitcast them.
494       return TypesRes;
495     }
496   }
497
498   // OK, types are bitcastable, now check constant contents.
499
500   if (L->isNullValue() && R->isNullValue())
501     return TypesRes;
502   if (L->isNullValue() && !R->isNullValue())
503     return 1;
504   if (!L->isNullValue() && R->isNullValue())
505     return -1;
506
507   if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
508     return Res;
509
510   switch (L->getValueID()) {
511   case Value::UndefValueVal: return TypesRes;
512   case Value::ConstantIntVal: {
513     const APInt &LInt = cast<ConstantInt>(L)->getValue();
514     const APInt &RInt = cast<ConstantInt>(R)->getValue();
515     return cmpAPInt(LInt, RInt);
516   }
517   case Value::ConstantFPVal: {
518     const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
519     const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
520     return cmpAPFloat(LAPF, RAPF);
521   }
522   case Value::ConstantArrayVal: {
523     const ConstantArray *LA = cast<ConstantArray>(L);
524     const ConstantArray *RA = cast<ConstantArray>(R);
525     uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
526     uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
527     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
528       return Res;
529     for (uint64_t i = 0; i < NumElementsL; ++i) {
530       if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
531                                  cast<Constant>(RA->getOperand(i))))
532         return Res;
533     }
534     return 0;
535   }
536   case Value::ConstantStructVal: {
537     const ConstantStruct *LS = cast<ConstantStruct>(L);
538     const ConstantStruct *RS = cast<ConstantStruct>(R);
539     unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
540     unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
541     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
542       return Res;
543     for (unsigned i = 0; i != NumElementsL; ++i) {
544       if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
545                                  cast<Constant>(RS->getOperand(i))))
546         return Res;
547     }
548     return 0;
549   }
550   case Value::ConstantVectorVal: {
551     const ConstantVector *LV = cast<ConstantVector>(L);
552     const ConstantVector *RV = cast<ConstantVector>(R);
553     unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
554     unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
555     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
556       return Res;
557     for (uint64_t i = 0; i < NumElementsL; ++i) {
558       if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
559                                  cast<Constant>(RV->getOperand(i))))
560         return Res;
561     }
562     return 0;
563   }
564   case Value::ConstantExprVal: {
565     const ConstantExpr *LE = cast<ConstantExpr>(L);
566     const ConstantExpr *RE = cast<ConstantExpr>(R);
567     unsigned NumOperandsL = LE->getNumOperands();
568     unsigned NumOperandsR = RE->getNumOperands();
569     if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
570       return Res;
571     for (unsigned i = 0; i < NumOperandsL; ++i) {
572       if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
573                                  cast<Constant>(RE->getOperand(i))))
574         return Res;
575     }
576     return 0;
577   }
578   case Value::FunctionVal:
579   case Value::GlobalVariableVal:
580   case Value::GlobalAliasVal:
581   default: // Unknown constant, cast L and R pointers to numbers and compare.
582     return cmpNumbers((uint64_t)L, (uint64_t)R);
583   }
584 }
585
586 /// cmpType - compares two types,
587 /// defines total ordering among the types set.
588 /// See method declaration comments for more details.
589 int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
590
591   PointerType *PTyL = dyn_cast<PointerType>(TyL);
592   PointerType *PTyR = dyn_cast<PointerType>(TyR);
593
594   if (DL) {
595     if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
596     if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
597   }
598
599   if (TyL == TyR)
600     return 0;
601
602   if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
603     return Res;
604
605   switch (TyL->getTypeID()) {
606   default:
607     llvm_unreachable("Unknown type!");
608     // Fall through in Release mode.
609   case Type::IntegerTyID:
610   case Type::VectorTyID:
611     // TyL == TyR would have returned true earlier.
612     return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
613
614   case Type::VoidTyID:
615   case Type::FloatTyID:
616   case Type::DoubleTyID:
617   case Type::X86_FP80TyID:
618   case Type::FP128TyID:
619   case Type::PPC_FP128TyID:
620   case Type::LabelTyID:
621   case Type::MetadataTyID:
622     return 0;
623
624   case Type::PointerTyID: {
625     assert(PTyL && PTyR && "Both types must be pointers here.");
626     return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
627   }
628
629   case Type::StructTyID: {
630     StructType *STyL = cast<StructType>(TyL);
631     StructType *STyR = cast<StructType>(TyR);
632     if (STyL->getNumElements() != STyR->getNumElements())
633       return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
634
635     if (STyL->isPacked() != STyR->isPacked())
636       return cmpNumbers(STyL->isPacked(), STyR->isPacked());
637
638     for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
639       if (int Res = cmpType(STyL->getElementType(i),
640                             STyR->getElementType(i)))
641         return Res;
642     }
643     return 0;
644   }
645
646   case Type::FunctionTyID: {
647     FunctionType *FTyL = cast<FunctionType>(TyL);
648     FunctionType *FTyR = cast<FunctionType>(TyR);
649     if (FTyL->getNumParams() != FTyR->getNumParams())
650       return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
651
652     if (FTyL->isVarArg() != FTyR->isVarArg())
653       return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
654
655     if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
656       return Res;
657
658     for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
659       if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
660         return Res;
661     }
662     return 0;
663   }
664
665   case Type::ArrayTyID: {
666     ArrayType *ATyL = cast<ArrayType>(TyL);
667     ArrayType *ATyR = cast<ArrayType>(TyR);
668     if (ATyL->getNumElements() != ATyR->getNumElements())
669       return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
670     return cmpType(ATyL->getElementType(), ATyR->getElementType());
671   }
672   }
673 }
674
675 // Determine whether the two operations are the same except that pointer-to-A
676 // and pointer-to-B are equivalent. This should be kept in sync with
677 // Instruction::isSameOperationAs.
678 bool FunctionComparator::isEquivalentOperation(const Instruction *I1,
679                                                const Instruction *I2) const {
680   // Differences from Instruction::isSameOperationAs:
681   //  * replace type comparison with calls to isEquivalentType.
682   //  * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
683   //  * because of the above, we don't test for the tail bit on calls later on
684   if (I1->getOpcode() != I2->getOpcode() ||
685       I1->getNumOperands() != I2->getNumOperands() ||
686       !isEquivalentType(I1->getType(), I2->getType()) ||
687       !I1->hasSameSubclassOptionalData(I2))
688     return false;
689
690   // We have two instructions of identical opcode and #operands.  Check to see
691   // if all operands are the same type
692   for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i)
693     if (!isEquivalentType(I1->getOperand(i)->getType(),
694                           I2->getOperand(i)->getType()))
695       return false;
696
697   // Check special state that is a part of some instructions.
698   if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
699     return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
700            LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() &&
701            LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
702            LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
703   if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
704     return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
705            SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() &&
706            SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
707            SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
708   if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
709     return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
710   if (const CallInst *CI = dyn_cast<CallInst>(I1))
711     return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
712            CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
713   if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
714     return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
715            CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes();
716   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
717     return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
718   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
719     return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
720   if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
721     return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
722            FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
723   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
724     return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
725            CXI->getSuccessOrdering() ==
726                cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
727            CXI->getFailureOrdering() ==
728                cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
729            CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
730   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
731     return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
732            RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
733            RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
734            RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
735
736   return true;
737 }
738
739 // Determine whether two GEP operations perform the same underlying arithmetic.
740 bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1,
741                                          const GEPOperator *GEP2) {
742   unsigned AS = GEP1->getPointerAddressSpace();
743   if (AS != GEP2->getPointerAddressSpace())
744     return false;
745
746   if (DL) {
747     // When we have target data, we can reduce the GEP down to the value in bytes
748     // added to the address.
749     unsigned BitWidth = DL ? DL->getPointerSizeInBits(AS) : 1;
750     APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0);
751     if (GEP1->accumulateConstantOffset(*DL, Offset1) &&
752         GEP2->accumulateConstantOffset(*DL, Offset2)) {
753       return Offset1 == Offset2;
754     }
755   }
756
757   if (GEP1->getPointerOperand()->getType() !=
758       GEP2->getPointerOperand()->getType())
759     return false;
760
761   if (GEP1->getNumOperands() != GEP2->getNumOperands())
762     return false;
763
764   for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) {
765     if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i)))
766       return false;
767   }
768
769   return true;
770 }
771
772 /// Compare two values used by the two functions under pair-wise comparison. If
773 /// this is the first time the values are seen, they're added to the mapping so
774 /// that we will detect mismatches on next use.
775 /// See comments in declaration for more details.
776 int FunctionComparator::cmpValues(const Value *L, const Value *R) {
777   // Catch self-reference case.
778   if (L == F1) {
779     if (R == F2)
780       return 0;
781     return -1;
782   }
783   if (R == F2) {
784     if (L == F1)
785       return 0;
786     return 1;
787   }
788
789   const Constant *ConstL = dyn_cast<Constant>(L);
790   const Constant *ConstR = dyn_cast<Constant>(R);
791   if (ConstL && ConstR) {
792     if (L == R)
793       return 0;
794     return cmpConstants(ConstL, ConstR);
795   }
796
797   if (ConstL)
798     return 1;
799   if (ConstR)
800     return -1;
801
802   const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
803   const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
804
805   if (InlineAsmL && InlineAsmR)
806     return cmpNumbers((uint64_t)L, (uint64_t)R);
807   if (InlineAsmL)
808     return 1;
809   if (InlineAsmR)
810     return -1;
811
812   auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
813        RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
814
815   return cmpNumbers(LeftSN.first->second, RightSN.first->second);
816 }
817 // Test whether two basic blocks have equivalent behaviour.
818 bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) {
819   BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end();
820   BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end();
821
822   do {
823     if (!enumerate(F1I, F2I))
824       return false;
825
826     if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) {
827       const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I);
828       if (!GEP2)
829         return false;
830
831       if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand()))
832         return false;
833
834       if (!isEquivalentGEP(GEP1, GEP2))
835         return false;
836     } else {
837       if (!isEquivalentOperation(F1I, F2I))
838         return false;
839
840       assert(F1I->getNumOperands() == F2I->getNumOperands());
841       for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
842         Value *OpF1 = F1I->getOperand(i);
843         Value *OpF2 = F2I->getOperand(i);
844
845         if (!enumerate(OpF1, OpF2))
846           return false;
847
848         if (OpF1->getValueID() != OpF2->getValueID() ||
849             !isEquivalentType(OpF1->getType(), OpF2->getType()))
850           return false;
851       }
852     }
853
854     ++F1I, ++F2I;
855   } while (F1I != F1E && F2I != F2E);
856
857   return F1I == F1E && F2I == F2E;
858 }
859
860 // Test whether the two functions have equivalent behaviour.
861 bool FunctionComparator::compare() {
862   // We need to recheck everything, but check the things that weren't included
863   // in the hash first.
864
865   sn_mapL.clear();
866   sn_mapR.clear();
867
868   if (F1->getAttributes() != F2->getAttributes())
869     return false;
870
871   if (F1->hasGC() != F2->hasGC())
872     return false;
873
874   if (F1->hasGC() && F1->getGC() != F2->getGC())
875     return false;
876
877   if (F1->hasSection() != F2->hasSection())
878     return false;
879
880   if (F1->hasSection() && F1->getSection() != F2->getSection())
881     return false;
882
883   if (F1->isVarArg() != F2->isVarArg())
884     return false;
885
886   // TODO: if it's internal and only used in direct calls, we could handle this
887   // case too.
888   if (F1->getCallingConv() != F2->getCallingConv())
889     return false;
890
891   if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
892     return false;
893
894   assert(F1->arg_size() == F2->arg_size() &&
895          "Identically typed functions have different numbers of args!");
896
897   // Visit the arguments so that they get enumerated in the order they're
898   // passed in.
899   for (Function::const_arg_iterator f1i = F1->arg_begin(),
900          f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
901     if (!enumerate(f1i, f2i))
902       llvm_unreachable("Arguments repeat!");
903   }
904
905   // We do a CFG-ordered walk since the actual ordering of the blocks in the
906   // linked list is immaterial. Our walk starts at the entry block for both
907   // functions, then takes each block from each terminator in order. As an
908   // artifact, this also means that unreachable blocks are ignored.
909   SmallVector<const BasicBlock *, 8> F1BBs, F2BBs;
910   SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
911
912   F1BBs.push_back(&F1->getEntryBlock());
913   F2BBs.push_back(&F2->getEntryBlock());
914
915   VisitedBBs.insert(F1BBs[0]);
916   while (!F1BBs.empty()) {
917     const BasicBlock *F1BB = F1BBs.pop_back_val();
918     const BasicBlock *F2BB = F2BBs.pop_back_val();
919
920     if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB))
921       return false;
922
923     const TerminatorInst *F1TI = F1BB->getTerminator();
924     const TerminatorInst *F2TI = F2BB->getTerminator();
925
926     assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors());
927     for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) {
928       if (!VisitedBBs.insert(F1TI->getSuccessor(i)))
929         continue;
930
931       F1BBs.push_back(F1TI->getSuccessor(i));
932       F2BBs.push_back(F2TI->getSuccessor(i));
933     }
934   }
935   return true;
936 }
937
938 namespace {
939
940 /// MergeFunctions finds functions which will generate identical machine code,
941 /// by considering all pointer types to be equivalent. Once identified,
942 /// MergeFunctions will fold them by replacing a call to one to a call to a
943 /// bitcast of the other.
944 ///
945 class MergeFunctions : public ModulePass {
946 public:
947   static char ID;
948   MergeFunctions()
949     : ModulePass(ID), HasGlobalAliases(false) {
950     initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
951   }
952
953   bool runOnModule(Module &M) override;
954
955 private:
956   typedef DenseSet<ComparableFunction> FnSetType;
957
958   /// A work queue of functions that may have been modified and should be
959   /// analyzed again.
960   std::vector<WeakVH> Deferred;
961
962   /// Insert a ComparableFunction into the FnSet, or merge it away if it's
963   /// equal to one that's already present.
964   bool insert(ComparableFunction &NewF);
965
966   /// Remove a Function from the FnSet and queue it up for a second sweep of
967   /// analysis.
968   void remove(Function *F);
969
970   /// Find the functions that use this Value and remove them from FnSet and
971   /// queue the functions.
972   void removeUsers(Value *V);
973
974   /// Replace all direct calls of Old with calls of New. Will bitcast New if
975   /// necessary to make types match.
976   void replaceDirectCallers(Function *Old, Function *New);
977
978   /// Merge two equivalent functions. Upon completion, G may be deleted, or may
979   /// be converted into a thunk. In either case, it should never be visited
980   /// again.
981   void mergeTwoFunctions(Function *F, Function *G);
982
983   /// Replace G with a thunk or an alias to F. Deletes G.
984   void writeThunkOrAlias(Function *F, Function *G);
985
986   /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
987   /// of G with bitcast(F). Deletes G.
988   void writeThunk(Function *F, Function *G);
989
990   /// Replace G with an alias to F. Deletes G.
991   void writeAlias(Function *F, Function *G);
992
993   /// The set of all distinct functions. Use the insert() and remove() methods
994   /// to modify it.
995   FnSetType FnSet;
996
997   /// DataLayout for more accurate GEP comparisons. May be NULL.
998   const DataLayout *DL;
999
1000   /// Whether or not the target supports global aliases.
1001   bool HasGlobalAliases;
1002 };
1003
1004 }  // end anonymous namespace
1005
1006 char MergeFunctions::ID = 0;
1007 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1008
1009 ModulePass *llvm::createMergeFunctionsPass() {
1010   return new MergeFunctions();
1011 }
1012
1013 bool MergeFunctions::runOnModule(Module &M) {
1014   bool Changed = false;
1015   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1016   DL = DLP ? &DLP->getDataLayout() : nullptr;
1017
1018   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1019     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
1020       Deferred.push_back(WeakVH(I));
1021   }
1022   FnSet.resize(Deferred.size());
1023
1024   do {
1025     std::vector<WeakVH> Worklist;
1026     Deferred.swap(Worklist);
1027
1028     DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1029     DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1030
1031     // Insert only strong functions and merge them. Strong function merging
1032     // always deletes one of them.
1033     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1034            E = Worklist.end(); I != E; ++I) {
1035       if (!*I) continue;
1036       Function *F = cast<Function>(*I);
1037       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1038           !F->mayBeOverridden()) {
1039         ComparableFunction CF = ComparableFunction(F, DL);
1040         Changed |= insert(CF);
1041       }
1042     }
1043
1044     // Insert only weak functions and merge them. By doing these second we
1045     // create thunks to the strong function when possible. When two weak
1046     // functions are identical, we create a new strong function with two weak
1047     // weak thunks to it which are identical but not mergable.
1048     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1049            E = Worklist.end(); I != E; ++I) {
1050       if (!*I) continue;
1051       Function *F = cast<Function>(*I);
1052       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1053           F->mayBeOverridden()) {
1054         ComparableFunction CF = ComparableFunction(F, DL);
1055         Changed |= insert(CF);
1056       }
1057     }
1058     DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
1059   } while (!Deferred.empty());
1060
1061   FnSet.clear();
1062
1063   return Changed;
1064 }
1065
1066 bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
1067                                                const ComparableFunction &RHS) {
1068   if (LHS.getFunc() == RHS.getFunc() &&
1069       LHS.getHash() == RHS.getHash())
1070     return true;
1071   if (!LHS.getFunc() || !RHS.getFunc())
1072     return false;
1073
1074   // One of these is a special "underlying pointer comparison only" object.
1075   if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
1076       RHS.getDataLayout() == ComparableFunction::LookupOnly)
1077     return false;
1078
1079   assert(LHS.getDataLayout() == RHS.getDataLayout() &&
1080          "Comparing functions for different targets");
1081
1082   return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(),
1083                             RHS.getFunc()).compare();
1084 }
1085
1086 // Replace direct callers of Old with New.
1087 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1088   Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
1089   for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1090     Use *U = &*UI;
1091     ++UI;
1092     CallSite CS(U->getUser());
1093     if (CS && CS.isCallee(U)) {
1094       remove(CS.getInstruction()->getParent()->getParent());
1095       U->set(BitcastNew);
1096     }
1097   }
1098 }
1099
1100 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1101 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
1102   if (HasGlobalAliases && G->hasUnnamedAddr()) {
1103     if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1104         G->hasWeakLinkage()) {
1105       writeAlias(F, G);
1106       return;
1107     }
1108   }
1109
1110   writeThunk(F, G);
1111 }
1112
1113 // Helper for writeThunk,
1114 // Selects proper bitcast operation,
1115 // but a bit simpler then CastInst::getCastOpcode.
1116 static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
1117   Type *SrcTy = V->getType();
1118   if (SrcTy->isStructTy()) {
1119     assert(DestTy->isStructTy());
1120     assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1121     Value *Result = UndefValue::get(DestTy);
1122     for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1123       Value *Element = createCast(
1124           Builder, Builder.CreateExtractValue(V, ArrayRef<unsigned int>(I)),
1125           DestTy->getStructElementType(I));
1126
1127       Result =
1128           Builder.CreateInsertValue(Result, Element, ArrayRef<unsigned int>(I));
1129     }
1130     return Result;
1131   }
1132   assert(!DestTy->isStructTy());
1133   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1134     return Builder.CreateIntToPtr(V, DestTy);
1135   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1136     return Builder.CreatePtrToInt(V, DestTy);
1137   else
1138     return Builder.CreateBitCast(V, DestTy);
1139 }
1140
1141 // Replace G with a simple tail call to bitcast(F). Also replace direct uses
1142 // of G with bitcast(F). Deletes G.
1143 void MergeFunctions::writeThunk(Function *F, Function *G) {
1144   if (!G->mayBeOverridden()) {
1145     // Redirect direct callers of G to F.
1146     replaceDirectCallers(G, F);
1147   }
1148
1149   // If G was internal then we may have replaced all uses of G with F. If so,
1150   // stop here and delete G. There's no need for a thunk.
1151   if (G->hasLocalLinkage() && G->use_empty()) {
1152     G->eraseFromParent();
1153     return;
1154   }
1155
1156   Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1157                                     G->getParent());
1158   BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
1159   IRBuilder<false> Builder(BB);
1160
1161   SmallVector<Value *, 16> Args;
1162   unsigned i = 0;
1163   FunctionType *FFTy = F->getFunctionType();
1164   for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1165        AI != AE; ++AI) {
1166     Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
1167     ++i;
1168   }
1169
1170   CallInst *CI = Builder.CreateCall(F, Args);
1171   CI->setTailCall();
1172   CI->setCallingConv(F->getCallingConv());
1173   if (NewG->getReturnType()->isVoidTy()) {
1174     Builder.CreateRetVoid();
1175   } else {
1176     Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
1177   }
1178
1179   NewG->copyAttributesFrom(G);
1180   NewG->takeName(G);
1181   removeUsers(G);
1182   G->replaceAllUsesWith(NewG);
1183   G->eraseFromParent();
1184
1185   DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
1186   ++NumThunksWritten;
1187 }
1188
1189 // Replace G with an alias to F and delete G.
1190 void MergeFunctions::writeAlias(Function *F, Function *G) {
1191   Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
1192   GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "",
1193                                     BitcastF, G->getParent());
1194   F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1195   GA->takeName(G);
1196   GA->setVisibility(G->getVisibility());
1197   removeUsers(G);
1198   G->replaceAllUsesWith(GA);
1199   G->eraseFromParent();
1200
1201   DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
1202   ++NumAliasesWritten;
1203 }
1204
1205 // Merge two equivalent functions. Upon completion, Function G is deleted.
1206 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
1207   if (F->mayBeOverridden()) {
1208     assert(G->mayBeOverridden());
1209
1210     if (HasGlobalAliases) {
1211       // Make them both thunks to the same internal function.
1212       Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1213                                      F->getParent());
1214       H->copyAttributesFrom(F);
1215       H->takeName(F);
1216       removeUsers(F);
1217       F->replaceAllUsesWith(H);
1218
1219       unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1220
1221       writeAlias(F, G);
1222       writeAlias(F, H);
1223
1224       F->setAlignment(MaxAlignment);
1225       F->setLinkage(GlobalValue::PrivateLinkage);
1226     } else {
1227       // We can't merge them. Instead, pick one and update all direct callers
1228       // to call it and hope that we improve the instruction cache hit rate.
1229       replaceDirectCallers(G, F);
1230     }
1231
1232     ++NumDoubleWeak;
1233   } else {
1234     writeThunkOrAlias(F, G);
1235   }
1236
1237   ++NumFunctionsMerged;
1238 }
1239
1240 // Insert a ComparableFunction into the FnSet, or merge it away if equal to one
1241 // that was already inserted.
1242 bool MergeFunctions::insert(ComparableFunction &NewF) {
1243   std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
1244   if (Result.second) {
1245     DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
1246     return false;
1247   }
1248
1249   const ComparableFunction &OldF = *Result.first;
1250
1251   // Don't merge tiny functions, since it can just end up making the function
1252   // larger.
1253   // FIXME: Should still merge them if they are unnamed_addr and produce an
1254   // alias.
1255   if (NewF.getFunc()->size() == 1) {
1256     if (NewF.getFunc()->front().size() <= 2) {
1257       DEBUG(dbgs() << NewF.getFunc()->getName()
1258             << " is to small to bother merging\n");
1259       return false;
1260     }
1261   }
1262
1263   // Never thunk a strong function to a weak function.
1264   assert(!OldF.getFunc()->mayBeOverridden() ||
1265          NewF.getFunc()->mayBeOverridden());
1266
1267   DEBUG(dbgs() << "  " << OldF.getFunc()->getName() << " == "
1268                << NewF.getFunc()->getName() << '\n');
1269
1270   Function *DeleteF = NewF.getFunc();
1271   NewF.release();
1272   mergeTwoFunctions(OldF.getFunc(), DeleteF);
1273   return true;
1274 }
1275
1276 // Remove a function from FnSet. If it was already in FnSet, add it to Deferred
1277 // so that we'll look at it in the next round.
1278 void MergeFunctions::remove(Function *F) {
1279   // We need to make sure we remove F, not a function "equal" to F per the
1280   // function equality comparator.
1281   //
1282   // The special "lookup only" ComparableFunction bypasses the expensive
1283   // function comparison in favour of a pointer comparison on the underlying
1284   // Function*'s.
1285   ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
1286   if (FnSet.erase(CF)) {
1287     DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
1288     Deferred.push_back(F);
1289   }
1290 }
1291
1292 // For each instruction used by the value, remove() the function that contains
1293 // the instruction. This should happen right before a call to RAUW.
1294 void MergeFunctions::removeUsers(Value *V) {
1295   std::vector<Value *> Worklist;
1296   Worklist.push_back(V);
1297   while (!Worklist.empty()) {
1298     Value *V = Worklist.back();
1299     Worklist.pop_back();
1300
1301     for (User *U : V->users()) {
1302       if (Instruction *I = dyn_cast<Instruction>(U)) {
1303         remove(I->getParent()->getParent());
1304       } else if (isa<GlobalValue>(U)) {
1305         // do nothing
1306       } else if (Constant *C = dyn_cast<Constant>(U)) {
1307         for (User *UU : C->users())
1308           Worklist.push_back(UU);
1309       }
1310     }
1311   }
1312 }