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 // Order relation is defined on set of functions. It was made through
13 // special function comparison procedure that returns
14 // 0 when functions are equal,
15 // -1 when Left function is less than right function, and
16 // 1 for opposite case. We need total-ordering, so we need to maintain
17 // four properties on the functions set:
18 // a <= a (reflexivity)
19 // if a <= b and b <= a then a = b (antisymmetry)
20 // if a <= b and b <= c then a <= c (transitivity).
21 // for all a and b: a <= b or b <= a (totality).
22 //
23 // Comparison iterates through each instruction in each basic block.
24 // Functions are kept on binary tree. For each new function F we perform
25 // lookup in binary tree.
26 // In practice it works the following way:
27 // -- We define Function* container class with custom "operator<" (FunctionPtr).
28 // -- "FunctionPtr" instances are stored in std::set collection, so every
29 //    std::set::insert operation will give you result in log(N) time.
30 //
31 // As an optimization, a hash of the function structure is calculated first, and
32 // two functions are only compared if they have the same hash. This hash is
33 // cheap to compute, and has the property that if function F == G according to
34 // the comparison function, then hash(F) == hash(G). This consistency property
35 // is critical to ensuring all possible merging opportunities are exploited.
36 // Collisions in the hash affect the speed of the pass but not the correctness
37 // or determinism of the resulting transformation.
38 //
39 // When a match is found the functions are folded. If both functions are
40 // overridable, we move the functionality into a new internal function and
41 // leave two overridable thunks to it.
42 //
43 //===----------------------------------------------------------------------===//
44 //
45 // Future work:
46 //
47 // * virtual functions.
48 //
49 // Many functions have their address taken by the virtual function table for
50 // the object they belong to. However, as long as it's only used for a lookup
51 // and call, this is irrelevant, and we'd like to fold such functions.
52 //
53 // * be smarter about bitcasts.
54 //
55 // In order to fold functions, we will sometimes add either bitcast instructions
56 // or bitcast constant expressions. Unfortunately, this can confound further
57 // analysis since the two functions differ where one has a bitcast and the
58 // other doesn't. We should learn to look through bitcasts.
59 //
60 // * Compare complex types with pointer types inside.
61 // * Compare cross-reference cases.
62 // * Compare complex expressions.
63 //
64 // All the three issues above could be described as ability to prove that
65 // fA == fB == fC == fE == fF == fG in example below:
66 //
67 //  void fA() {
68 //    fB();
69 //  }
70 //  void fB() {
71 //    fA();
72 //  }
73 //
74 //  void fE() {
75 //    fF();
76 //  }
77 //  void fF() {
78 //    fG();
79 //  }
80 //  void fG() {
81 //    fE();
82 //  }
83 //
84 // Simplest cross-reference case (fA <--> fB) was implemented in previous
85 // versions of MergeFunctions, though it presented only in two function pairs
86 // in test-suite (that counts >50k functions)
87 // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
88 // could cover much more cases.
89 //
90 //===----------------------------------------------------------------------===//
91 
92 #include "llvm/Transforms/IPO.h"
93 #include "llvm/ADT/DenseSet.h"
94 #include "llvm/ADT/FoldingSet.h"
95 #include "llvm/ADT/STLExtras.h"
96 #include "llvm/ADT/SmallSet.h"
97 #include "llvm/ADT/Statistic.h"
98 #include "llvm/ADT/Hashing.h"
99 #include "llvm/IR/CallSite.h"
100 #include "llvm/IR/Constants.h"
101 #include "llvm/IR/DataLayout.h"
102 #include "llvm/IR/IRBuilder.h"
103 #include "llvm/IR/InlineAsm.h"
104 #include "llvm/IR/Instructions.h"
105 #include "llvm/IR/LLVMContext.h"
106 #include "llvm/IR/Module.h"
107 #include "llvm/IR/Operator.h"
108 #include "llvm/IR/ValueHandle.h"
109 #include "llvm/IR/ValueMap.h"
110 #include "llvm/Pass.h"
111 #include "llvm/Support/CommandLine.h"
112 #include "llvm/Support/Debug.h"
113 #include "llvm/Support/ErrorHandling.h"
114 #include "llvm/Support/raw_ostream.h"
115 #include <vector>
116 
117 using namespace llvm;
118 
119 #define DEBUG_TYPE "mergefunc"
120 
121 STATISTIC(NumFunctionsMerged, "Number of functions merged");
122 STATISTIC(NumThunksWritten, "Number of thunks generated");
123 STATISTIC(NumAliasesWritten, "Number of aliases generated");
124 STATISTIC(NumDoubleWeak, "Number of new functions created");
125 
126 static cl::opt<unsigned> NumFunctionsForSanityCheck(
127     "mergefunc-sanity",
128     cl::desc("How many functions in module could be used for "
129              "MergeFunctions pass sanity check. "
130              "'0' disables this check. Works only with '-debug' key."),
131     cl::init(0), cl::Hidden);
132 
133 namespace {
134 
135 /// GlobalNumberState assigns an integer to each global value in the program,
136 /// which is used by the comparison routine to order references to globals. This
137 /// state must be preserved throughout the pass, because Functions and other
138 /// globals need to maintain their relative order. Globals are assigned a number
139 /// when they are first visited. This order is deterministic, and so the
140 /// assigned numbers are as well. When two functions are merged, neither number
141 /// is updated. If the symbols are weak, this would be incorrect. If they are
142 /// strong, then one will be replaced at all references to the other, and so
143 /// direct callsites will now see one or the other symbol, and no update is
144 /// necessary. Note that if we were guaranteed unique names, we could just
145 /// compare those, but this would not work for stripped bitcodes or for those
146 /// few symbols without a name.
147 class GlobalNumberState {
148   struct Config : ValueMapConfig<GlobalValue*> {
149     enum { FollowRAUW = false };
150   };
151   // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW
152   // occurs, the mapping does not change. Tracking changes is unnecessary, and
153   // also problematic for weak symbols (which may be overwritten).
154   typedef ValueMap<GlobalValue *, uint64_t, Config> ValueNumberMap;
155   ValueNumberMap GlobalNumbers;
156   // The next unused serial number to assign to a global.
157   uint64_t NextNumber;
158   public:
159     GlobalNumberState() : GlobalNumbers(), NextNumber(0) {}
160     uint64_t getNumber(GlobalValue* Global) {
161       ValueNumberMap::iterator MapIter;
162       bool Inserted;
163       std::tie(MapIter, Inserted) = GlobalNumbers.insert({Global, NextNumber});
164       if (Inserted)
165         NextNumber++;
166       return MapIter->second;
167     }
168     void clear() {
169       GlobalNumbers.clear();
170     }
171 };
172 
173 /// FunctionComparator - Compares two functions to determine whether or not
174 /// they will generate machine code with the same behaviour. DataLayout is
175 /// used if available. The comparator always fails conservatively (erring on the
176 /// side of claiming that two functions are different).
177 class FunctionComparator {
178 public:
179   FunctionComparator(const Function *F1, const Function *F2,
180                      GlobalNumberState* GN)
181       : FnL(F1), FnR(F2), GlobalNumbers(GN) {}
182 
183   /// Test whether the two functions have equivalent behaviour.
184   int compare();
185   /// Hash a function. Equivalent functions will have the same hash, and unequal
186   /// functions will have different hashes with high probability.
187   typedef uint64_t FunctionHash;
188   static FunctionHash functionHash(Function &);
189 
190 private:
191   /// Test whether two basic blocks have equivalent behaviour.
192   int cmpBasicBlocks(const BasicBlock *BBL, const BasicBlock *BBR) const;
193 
194   /// Constants comparison.
195   /// Its analog to lexicographical comparison between hypothetical numbers
196   /// of next format:
197   /// <bitcastability-trait><raw-bit-contents>
198   ///
199   /// 1. Bitcastability.
200   /// Check whether L's type could be losslessly bitcasted to R's type.
201   /// On this stage method, in case when lossless bitcast is not possible
202   /// method returns -1 or 1, thus also defining which type is greater in
203   /// context of bitcastability.
204   /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
205   ///          to the contents comparison.
206   ///          If types differ, remember types comparison result and check
207   ///          whether we still can bitcast types.
208   /// Stage 1: Types that satisfies isFirstClassType conditions are always
209   ///          greater then others.
210   /// Stage 2: Vector is greater then non-vector.
211   ///          If both types are vectors, then vector with greater bitwidth is
212   ///          greater.
213   ///          If both types are vectors with the same bitwidth, then types
214   ///          are bitcastable, and we can skip other stages, and go to contents
215   ///          comparison.
216   /// Stage 3: Pointer types are greater than non-pointers. If both types are
217   ///          pointers of the same address space - go to contents comparison.
218   ///          Different address spaces: pointer with greater address space is
219   ///          greater.
220   /// Stage 4: Types are neither vectors, nor pointers. And they differ.
221   ///          We don't know how to bitcast them. So, we better don't do it,
222   ///          and return types comparison result (so it determines the
223   ///          relationship among constants we don't know how to bitcast).
224   ///
225   /// Just for clearance, let's see how the set of constants could look
226   /// on single dimension axis:
227   ///
228   /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
229   /// Where: NFCT - Not a FirstClassType
230   ///        FCT - FirstClassTyp:
231   ///
232   /// 2. Compare raw contents.
233   /// It ignores types on this stage and only compares bits from L and R.
234   /// Returns 0, if L and R has equivalent contents.
235   /// -1 or 1 if values are different.
236   /// Pretty trivial:
237   /// 2.1. If contents are numbers, compare numbers.
238   ///    Ints with greater bitwidth are greater. Ints with same bitwidths
239   ///    compared by their contents.
240   /// 2.2. "And so on". Just to avoid discrepancies with comments
241   /// perhaps it would be better to read the implementation itself.
242   /// 3. And again about overall picture. Let's look back at how the ordered set
243   /// of constants will look like:
244   /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
245   ///
246   /// Now look, what could be inside [FCT, "others"], for example:
247   /// [FCT, "others"] =
248   /// [
249   ///   [double 0.1], [double 1.23],
250   ///   [i32 1], [i32 2],
251   ///   { double 1.0 },       ; StructTyID, NumElements = 1
252   ///   { i32 1 },            ; StructTyID, NumElements = 1
253   ///   { double 1, i32 1 },  ; StructTyID, NumElements = 2
254   ///   { i32 1, double 1 }   ; StructTyID, NumElements = 2
255   /// ]
256   ///
257   /// Let's explain the order. Float numbers will be less than integers, just
258   /// because of cmpType terms: FloatTyID < IntegerTyID.
259   /// Floats (with same fltSemantics) are sorted according to their value.
260   /// Then you can see integers, and they are, like a floats,
261   /// could be easy sorted among each others.
262   /// The structures. Structures are grouped at the tail, again because of their
263   /// TypeID: StructTyID > IntegerTyID > FloatTyID.
264   /// Structures with greater number of elements are greater. Structures with
265   /// greater elements going first are greater.
266   /// The same logic with vectors, arrays and other possible complex types.
267   ///
268   /// Bitcastable constants.
269   /// Let's assume, that some constant, belongs to some group of
270   /// "so-called-equal" values with different types, and at the same time
271   /// belongs to another group of constants with equal types
272   /// and "really" equal values.
273   ///
274   /// Now, prove that this is impossible:
275   ///
276   /// If constant A with type TyA is bitcastable to B with type TyB, then:
277   /// 1. All constants with equal types to TyA, are bitcastable to B. Since
278   ///    those should be vectors (if TyA is vector), pointers
279   ///    (if TyA is pointer), or else (if TyA equal to TyB), those types should
280   ///    be equal to TyB.
281   /// 2. All constants with non-equal, but bitcastable types to TyA, are
282   ///    bitcastable to B.
283   ///    Once again, just because we allow it to vectors and pointers only.
284   ///    This statement could be expanded as below:
285   /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
286   ///      vector B, and thus bitcastable to B as well.
287   /// 2.2. All pointers of the same address space, no matter what they point to,
288   ///      bitcastable. So if C is pointer, it could be bitcasted to A and to B.
289   /// So any constant equal or bitcastable to A is equal or bitcastable to B.
290   /// QED.
291   ///
292   /// In another words, for pointers and vectors, we ignore top-level type and
293   /// look at their particular properties (bit-width for vectors, and
294   /// address space for pointers).
295   /// If these properties are equal - compare their contents.
296   int cmpConstants(const Constant *L, const Constant *R) const;
297 
298   /// Compares two global values by number. Uses the GlobalNumbersState to
299   /// identify the same gobals across function calls.
300   int cmpGlobalValues(GlobalValue *L, GlobalValue *R) const;
301 
302   /// Assign or look up previously assigned numbers for the two values, and
303   /// return whether the numbers are equal. Numbers are assigned in the order
304   /// visited.
305   /// Comparison order:
306   /// Stage 0: Value that is function itself is always greater then others.
307   ///          If left and right values are references to their functions, then
308   ///          they are equal.
309   /// Stage 1: Constants are greater than non-constants.
310   ///          If both left and right are constants, then the result of
311   ///          cmpConstants is used as cmpValues result.
312   /// Stage 2: InlineAsm instances are greater than others. If both left and
313   ///          right are InlineAsm instances, InlineAsm* pointers casted to
314   ///          integers and compared as numbers.
315   /// Stage 3: For all other cases we compare order we meet these values in
316   ///          their functions. If right value was met first during scanning,
317   ///          then left value is greater.
318   ///          In another words, we compare serial numbers, for more details
319   ///          see comments for sn_mapL and sn_mapR.
320   int cmpValues(const Value *L, const Value *R) const;
321 
322   /// Compare two Instructions for equivalence, similar to
323   /// Instruction::isSameOperationAs.
324   ///
325   /// Stages are listed in "most significant stage first" order:
326   /// On each stage below, we do comparison between some left and right
327   /// operation parts. If parts are non-equal, we assign parts comparison
328   /// result to the operation comparison result and exit from method.
329   /// Otherwise we proceed to the next stage.
330   /// Stages:
331   /// 1. Operations opcodes. Compared as numbers.
332   /// 2. Number of operands.
333   /// 3. Operation types. Compared with cmpType method.
334   /// 4. Compare operation subclass optional data as stream of bytes:
335   /// just convert it to integers and call cmpNumbers.
336   /// 5. Compare in operation operand types with cmpType in
337   /// most significant operand first order.
338   /// 6. Last stage. Check operations for some specific attributes.
339   /// For example, for Load it would be:
340   /// 6.1.Load: volatile (as boolean flag)
341   /// 6.2.Load: alignment (as integer numbers)
342   /// 6.3.Load: ordering (as underlying enum class value)
343   /// 6.4.Load: synch-scope (as integer numbers)
344   /// 6.5.Load: range metadata (as integer ranges)
345   /// On this stage its better to see the code, since its not more than 10-15
346   /// strings for particular instruction, and could change sometimes.
347   int cmpOperations(const Instruction *L, const Instruction *R) const;
348 
349   /// Compare two GEPs for equivalent pointer arithmetic.
350   /// Parts to be compared for each comparison stage,
351   /// most significant stage first:
352   /// 1. Address space. As numbers.
353   /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
354   /// 3. Pointer operand type (using cmpType method).
355   /// 4. Number of operands.
356   /// 5. Compare operands, using cmpValues method.
357   int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR) const;
358   int cmpGEPs(const GetElementPtrInst *GEPL,
359               const GetElementPtrInst *GEPR) const {
360     return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
361   }
362 
363   /// cmpType - compares two types,
364   /// defines total ordering among the types set.
365   ///
366   /// Return values:
367   /// 0 if types are equal,
368   /// -1 if Left is less than Right,
369   /// +1 if Left is greater than Right.
370   ///
371   /// Description:
372   /// Comparison is broken onto stages. Like in lexicographical comparison
373   /// stage coming first has higher priority.
374   /// On each explanation stage keep in mind total ordering properties.
375   ///
376   /// 0. Before comparison we coerce pointer types of 0 address space to
377   /// integer.
378   /// We also don't bother with same type at left and right, so
379   /// just return 0 in this case.
380   ///
381   /// 1. If types are of different kind (different type IDs).
382   ///    Return result of type IDs comparison, treating them as numbers.
383   /// 2. If types are integers, check that they have the same width. If they
384   /// are vectors, check that they have the same count and subtype.
385   /// 3. Types have the same ID, so check whether they are one of:
386   /// * Void
387   /// * Float
388   /// * Double
389   /// * X86_FP80
390   /// * FP128
391   /// * PPC_FP128
392   /// * Label
393   /// * Metadata
394   /// We can treat these types as equal whenever their IDs are same.
395   /// 4. If Left and Right are pointers, return result of address space
396   /// comparison (numbers comparison). We can treat pointer types of same
397   /// address space as equal.
398   /// 5. If types are complex.
399   /// Then both Left and Right are to be expanded and their element types will
400   /// be checked with the same way. If we get Res != 0 on some stage, return it.
401   /// Otherwise return 0.
402   /// 6. For all other cases put llvm_unreachable.
403   int cmpTypes(Type *TyL, Type *TyR) const;
404 
405   int cmpNumbers(uint64_t L, uint64_t R) const;
406   int cmpOrderings(AtomicOrdering L, AtomicOrdering R) const;
407   int cmpAPInts(const APInt &L, const APInt &R) const;
408   int cmpAPFloats(const APFloat &L, const APFloat &R) const;
409   int cmpInlineAsm(const InlineAsm *L, const InlineAsm *R) const;
410   int cmpMem(StringRef L, StringRef R) const;
411   int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
412   int cmpRangeMetadata(const MDNode *L, const MDNode *R) const;
413   int cmpOperandBundlesSchema(const Instruction *L, const Instruction *R) const;
414 
415   // The two functions undergoing comparison.
416   const Function *FnL, *FnR;
417 
418   /// Assign serial numbers to values from left function, and values from
419   /// right function.
420   /// Explanation:
421   /// Being comparing functions we need to compare values we meet at left and
422   /// right sides.
423   /// Its easy to sort things out for external values. It just should be
424   /// the same value at left and right.
425   /// But for local values (those were introduced inside function body)
426   /// we have to ensure they were introduced at exactly the same place,
427   /// and plays the same role.
428   /// Let's assign serial number to each value when we meet it first time.
429   /// Values that were met at same place will be with same serial numbers.
430   /// In this case it would be good to explain few points about values assigned
431   /// to BBs and other ways of implementation (see below).
432   ///
433   /// 1. Safety of BB reordering.
434   /// It's safe to change the order of BasicBlocks in function.
435   /// Relationship with other functions and serial numbering will not be
436   /// changed in this case.
437   /// As follows from FunctionComparator::compare(), we do CFG walk: we start
438   /// from the entry, and then take each terminator. So it doesn't matter how in
439   /// fact BBs are ordered in function. And since cmpValues are called during
440   /// this walk, the numbering depends only on how BBs located inside the CFG.
441   /// So the answer is - yes. We will get the same numbering.
442   ///
443   /// 2. Impossibility to use dominance properties of values.
444   /// If we compare two instruction operands: first is usage of local
445   /// variable AL from function FL, and second is usage of local variable AR
446   /// from FR, we could compare their origins and check whether they are
447   /// defined at the same place.
448   /// But, we are still not able to compare operands of PHI nodes, since those
449   /// could be operands from further BBs we didn't scan yet.
450   /// So it's impossible to use dominance properties in general.
451   mutable DenseMap<const Value*, int> sn_mapL, sn_mapR;
452 
453   // The global state we will use
454   GlobalNumberState* GlobalNumbers;
455 };
456 
457 class FunctionNode {
458   mutable AssertingVH<Function> F;
459   FunctionComparator::FunctionHash Hash;
460 public:
461   // Note the hash is recalculated potentially multiple times, but it is cheap.
462   FunctionNode(Function *F)
463     : F(F), Hash(FunctionComparator::functionHash(*F))  {}
464   Function *getFunc() const { return F; }
465   FunctionComparator::FunctionHash getHash() const { return Hash; }
466 
467   /// Replace the reference to the function F by the function G, assuming their
468   /// implementations are equal.
469   void replaceBy(Function *G) const {
470     F = G;
471   }
472 
473   void release() { F = nullptr; }
474 };
475 } // end anonymous namespace
476 
477 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
478   if (L < R) return -1;
479   if (L > R) return 1;
480   return 0;
481 }
482 
483 int FunctionComparator::cmpOrderings(AtomicOrdering L, AtomicOrdering R) const {
484   if ((int)L < (int)R) return -1;
485   if ((int)L > (int)R) return 1;
486   return 0;
487 }
488 
489 int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
490   if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
491     return Res;
492   if (L.ugt(R)) return 1;
493   if (R.ugt(L)) return -1;
494   return 0;
495 }
496 
497 int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
498   // Floats are ordered first by semantics (i.e. float, double, half, etc.),
499   // then by value interpreted as a bitstring (aka APInt).
500   const fltSemantics &SL = L.getSemantics(), &SR = R.getSemantics();
501   if (int Res = cmpNumbers(APFloat::semanticsPrecision(SL),
502                            APFloat::semanticsPrecision(SR)))
503     return Res;
504   if (int Res = cmpNumbers(APFloat::semanticsMaxExponent(SL),
505                            APFloat::semanticsMaxExponent(SR)))
506     return Res;
507   if (int Res = cmpNumbers(APFloat::semanticsMinExponent(SL),
508                            APFloat::semanticsMinExponent(SR)))
509     return Res;
510   if (int Res = cmpNumbers(APFloat::semanticsSizeInBits(SL),
511                            APFloat::semanticsSizeInBits(SR)))
512     return Res;
513   return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
514 }
515 
516 int FunctionComparator::cmpMem(StringRef L, StringRef R) const {
517   // Prevent heavy comparison, compare sizes first.
518   if (int Res = cmpNumbers(L.size(), R.size()))
519     return Res;
520 
521   // Compare strings lexicographically only when it is necessary: only when
522   // strings are equal in size.
523   return L.compare(R);
524 }
525 
526 int FunctionComparator::cmpAttrs(const AttributeSet L,
527                                  const AttributeSet R) const {
528   if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
529     return Res;
530 
531   for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
532     AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
533                            RE = R.end(i);
534     for (; LI != LE && RI != RE; ++LI, ++RI) {
535       Attribute LA = *LI;
536       Attribute RA = *RI;
537       if (LA < RA)
538         return -1;
539       if (RA < LA)
540         return 1;
541     }
542     if (LI != LE)
543       return 1;
544     if (RI != RE)
545       return -1;
546   }
547   return 0;
548 }
549 
550 int FunctionComparator::cmpRangeMetadata(const MDNode *L,
551                                          const MDNode *R) const {
552   if (L == R)
553     return 0;
554   if (!L)
555     return -1;
556   if (!R)
557     return 1;
558   // Range metadata is a sequence of numbers. Make sure they are the same
559   // sequence.
560   // TODO: Note that as this is metadata, it is possible to drop and/or merge
561   // this data when considering functions to merge. Thus this comparison would
562   // return 0 (i.e. equivalent), but merging would become more complicated
563   // because the ranges would need to be unioned. It is not likely that
564   // functions differ ONLY in this metadata if they are actually the same
565   // function semantically.
566   if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
567     return Res;
568   for (size_t I = 0; I < L->getNumOperands(); ++I) {
569     ConstantInt *LLow = mdconst::extract<ConstantInt>(L->getOperand(I));
570     ConstantInt *RLow = mdconst::extract<ConstantInt>(R->getOperand(I));
571     if (int Res = cmpAPInts(LLow->getValue(), RLow->getValue()))
572       return Res;
573   }
574   return 0;
575 }
576 
577 int FunctionComparator::cmpOperandBundlesSchema(const Instruction *L,
578                                                 const Instruction *R) const {
579   ImmutableCallSite LCS(L);
580   ImmutableCallSite RCS(R);
581 
582   assert(LCS && RCS && "Must be calls or invokes!");
583   assert(LCS.isCall() == RCS.isCall() && "Can't compare otherwise!");
584 
585   if (int Res =
586           cmpNumbers(LCS.getNumOperandBundles(), RCS.getNumOperandBundles()))
587     return Res;
588 
589   for (unsigned i = 0, e = LCS.getNumOperandBundles(); i != e; ++i) {
590     auto OBL = LCS.getOperandBundleAt(i);
591     auto OBR = RCS.getOperandBundleAt(i);
592 
593     if (int Res = OBL.getTagName().compare(OBR.getTagName()))
594       return Res;
595 
596     if (int Res = cmpNumbers(OBL.Inputs.size(), OBR.Inputs.size()))
597       return Res;
598   }
599 
600   return 0;
601 }
602 
603 /// Constants comparison:
604 /// 1. Check whether type of L constant could be losslessly bitcasted to R
605 /// type.
606 /// 2. Compare constant contents.
607 /// For more details see declaration comments.
608 int FunctionComparator::cmpConstants(const Constant *L,
609                                      const Constant *R) const {
610 
611   Type *TyL = L->getType();
612   Type *TyR = R->getType();
613 
614   // Check whether types are bitcastable. This part is just re-factored
615   // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
616   // we also pack into result which type is "less" for us.
617   int TypesRes = cmpTypes(TyL, TyR);
618   if (TypesRes != 0) {
619     // Types are different, but check whether we can bitcast them.
620     if (!TyL->isFirstClassType()) {
621       if (TyR->isFirstClassType())
622         return -1;
623       // Neither TyL nor TyR are values of first class type. Return the result
624       // of comparing the types
625       return TypesRes;
626     }
627     if (!TyR->isFirstClassType()) {
628       if (TyL->isFirstClassType())
629         return 1;
630       return TypesRes;
631     }
632 
633     // Vector -> Vector conversions are always lossless if the two vector types
634     // have the same size, otherwise not.
635     unsigned TyLWidth = 0;
636     unsigned TyRWidth = 0;
637 
638     if (auto *VecTyL = dyn_cast<VectorType>(TyL))
639       TyLWidth = VecTyL->getBitWidth();
640     if (auto *VecTyR = dyn_cast<VectorType>(TyR))
641       TyRWidth = VecTyR->getBitWidth();
642 
643     if (TyLWidth != TyRWidth)
644       return cmpNumbers(TyLWidth, TyRWidth);
645 
646     // Zero bit-width means neither TyL nor TyR are vectors.
647     if (!TyLWidth) {
648       PointerType *PTyL = dyn_cast<PointerType>(TyL);
649       PointerType *PTyR = dyn_cast<PointerType>(TyR);
650       if (PTyL && PTyR) {
651         unsigned AddrSpaceL = PTyL->getAddressSpace();
652         unsigned AddrSpaceR = PTyR->getAddressSpace();
653         if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
654           return Res;
655       }
656       if (PTyL)
657         return 1;
658       if (PTyR)
659         return -1;
660 
661       // TyL and TyR aren't vectors, nor pointers. We don't know how to
662       // bitcast them.
663       return TypesRes;
664     }
665   }
666 
667   // OK, types are bitcastable, now check constant contents.
668 
669   if (L->isNullValue() && R->isNullValue())
670     return TypesRes;
671   if (L->isNullValue() && !R->isNullValue())
672     return 1;
673   if (!L->isNullValue() && R->isNullValue())
674     return -1;
675 
676   auto GlobalValueL = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(L));
677   auto GlobalValueR = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(R));
678   if (GlobalValueL && GlobalValueR) {
679     return cmpGlobalValues(GlobalValueL, GlobalValueR);
680   }
681 
682   if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
683     return Res;
684 
685   if (const auto *SeqL = dyn_cast<ConstantDataSequential>(L)) {
686     const auto *SeqR = cast<ConstantDataSequential>(R);
687     // This handles ConstantDataArray and ConstantDataVector. Note that we
688     // compare the two raw data arrays, which might differ depending on the host
689     // endianness. This isn't a problem though, because the endiness of a module
690     // will affect the order of the constants, but this order is the same
691     // for a given input module and host platform.
692     return cmpMem(SeqL->getRawDataValues(), SeqR->getRawDataValues());
693   }
694 
695   switch (L->getValueID()) {
696   case Value::UndefValueVal:
697   case Value::ConstantTokenNoneVal:
698     return TypesRes;
699   case Value::ConstantIntVal: {
700     const APInt &LInt = cast<ConstantInt>(L)->getValue();
701     const APInt &RInt = cast<ConstantInt>(R)->getValue();
702     return cmpAPInts(LInt, RInt);
703   }
704   case Value::ConstantFPVal: {
705     const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
706     const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
707     return cmpAPFloats(LAPF, RAPF);
708   }
709   case Value::ConstantArrayVal: {
710     const ConstantArray *LA = cast<ConstantArray>(L);
711     const ConstantArray *RA = cast<ConstantArray>(R);
712     uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
713     uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
714     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
715       return Res;
716     for (uint64_t i = 0; i < NumElementsL; ++i) {
717       if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
718                                  cast<Constant>(RA->getOperand(i))))
719         return Res;
720     }
721     return 0;
722   }
723   case Value::ConstantStructVal: {
724     const ConstantStruct *LS = cast<ConstantStruct>(L);
725     const ConstantStruct *RS = cast<ConstantStruct>(R);
726     unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
727     unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
728     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
729       return Res;
730     for (unsigned i = 0; i != NumElementsL; ++i) {
731       if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
732                                  cast<Constant>(RS->getOperand(i))))
733         return Res;
734     }
735     return 0;
736   }
737   case Value::ConstantVectorVal: {
738     const ConstantVector *LV = cast<ConstantVector>(L);
739     const ConstantVector *RV = cast<ConstantVector>(R);
740     unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
741     unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
742     if (int Res = cmpNumbers(NumElementsL, NumElementsR))
743       return Res;
744     for (uint64_t i = 0; i < NumElementsL; ++i) {
745       if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
746                                  cast<Constant>(RV->getOperand(i))))
747         return Res;
748     }
749     return 0;
750   }
751   case Value::ConstantExprVal: {
752     const ConstantExpr *LE = cast<ConstantExpr>(L);
753     const ConstantExpr *RE = cast<ConstantExpr>(R);
754     unsigned NumOperandsL = LE->getNumOperands();
755     unsigned NumOperandsR = RE->getNumOperands();
756     if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
757       return Res;
758     for (unsigned i = 0; i < NumOperandsL; ++i) {
759       if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
760                                  cast<Constant>(RE->getOperand(i))))
761         return Res;
762     }
763     return 0;
764   }
765   case Value::BlockAddressVal: {
766     const BlockAddress *LBA = cast<BlockAddress>(L);
767     const BlockAddress *RBA = cast<BlockAddress>(R);
768     if (int Res = cmpValues(LBA->getFunction(), RBA->getFunction()))
769       return Res;
770     if (LBA->getFunction() == RBA->getFunction()) {
771       // They are BBs in the same function. Order by which comes first in the
772       // BB order of the function. This order is deterministic.
773       Function* F = LBA->getFunction();
774       BasicBlock *LBB = LBA->getBasicBlock();
775       BasicBlock *RBB = RBA->getBasicBlock();
776       if (LBB == RBB)
777         return 0;
778       for(BasicBlock &BB : F->getBasicBlockList()) {
779         if (&BB == LBB) {
780           assert(&BB != RBB);
781           return -1;
782         }
783         if (&BB == RBB)
784           return 1;
785       }
786       llvm_unreachable("Basic Block Address does not point to a basic block in "
787                        "its function.");
788       return -1;
789     } else {
790       // cmpValues said the functions are the same. So because they aren't
791       // literally the same pointer, they must respectively be the left and
792       // right functions.
793       assert(LBA->getFunction() == FnL && RBA->getFunction() == FnR);
794       // cmpValues will tell us if these are equivalent BasicBlocks, in the
795       // context of their respective functions.
796       return cmpValues(LBA->getBasicBlock(), RBA->getBasicBlock());
797     }
798   }
799   default: // Unknown constant, abort.
800     DEBUG(dbgs() << "Looking at valueID " << L->getValueID() << "\n");
801     llvm_unreachable("Constant ValueID not recognized.");
802     return -1;
803   }
804 }
805 
806 int FunctionComparator::cmpGlobalValues(GlobalValue *L, GlobalValue *R) const {
807   return cmpNumbers(GlobalNumbers->getNumber(L), GlobalNumbers->getNumber(R));
808 }
809 
810 /// cmpType - compares two types,
811 /// defines total ordering among the types set.
812 /// See method declaration comments for more details.
813 int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
814   PointerType *PTyL = dyn_cast<PointerType>(TyL);
815   PointerType *PTyR = dyn_cast<PointerType>(TyR);
816 
817   const DataLayout &DL = FnL->getParent()->getDataLayout();
818   if (PTyL && PTyL->getAddressSpace() == 0)
819     TyL = DL.getIntPtrType(TyL);
820   if (PTyR && PTyR->getAddressSpace() == 0)
821     TyR = DL.getIntPtrType(TyR);
822 
823   if (TyL == TyR)
824     return 0;
825 
826   if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
827     return Res;
828 
829   switch (TyL->getTypeID()) {
830   default:
831     llvm_unreachable("Unknown type!");
832     // Fall through in Release mode.
833   case Type::IntegerTyID:
834     return cmpNumbers(cast<IntegerType>(TyL)->getBitWidth(),
835                       cast<IntegerType>(TyR)->getBitWidth());
836   case Type::VectorTyID: {
837     VectorType *VTyL = cast<VectorType>(TyL), *VTyR = cast<VectorType>(TyR);
838     if (int Res = cmpNumbers(VTyL->getNumElements(), VTyR->getNumElements()))
839       return Res;
840     return cmpTypes(VTyL->getElementType(), VTyR->getElementType());
841   }
842   // TyL == TyR would have returned true earlier, because types are uniqued.
843   case Type::VoidTyID:
844   case Type::FloatTyID:
845   case Type::DoubleTyID:
846   case Type::X86_FP80TyID:
847   case Type::FP128TyID:
848   case Type::PPC_FP128TyID:
849   case Type::LabelTyID:
850   case Type::MetadataTyID:
851   case Type::TokenTyID:
852     return 0;
853 
854   case Type::PointerTyID: {
855     assert(PTyL && PTyR && "Both types must be pointers here.");
856     return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
857   }
858 
859   case Type::StructTyID: {
860     StructType *STyL = cast<StructType>(TyL);
861     StructType *STyR = cast<StructType>(TyR);
862     if (STyL->getNumElements() != STyR->getNumElements())
863       return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
864 
865     if (STyL->isPacked() != STyR->isPacked())
866       return cmpNumbers(STyL->isPacked(), STyR->isPacked());
867 
868     for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
869       if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
870         return Res;
871     }
872     return 0;
873   }
874 
875   case Type::FunctionTyID: {
876     FunctionType *FTyL = cast<FunctionType>(TyL);
877     FunctionType *FTyR = cast<FunctionType>(TyR);
878     if (FTyL->getNumParams() != FTyR->getNumParams())
879       return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
880 
881     if (FTyL->isVarArg() != FTyR->isVarArg())
882       return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
883 
884     if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
885       return Res;
886 
887     for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
888       if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
889         return Res;
890     }
891     return 0;
892   }
893 
894   case Type::ArrayTyID: {
895     ArrayType *ATyL = cast<ArrayType>(TyL);
896     ArrayType *ATyR = cast<ArrayType>(TyR);
897     if (ATyL->getNumElements() != ATyR->getNumElements())
898       return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
899     return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
900   }
901   }
902 }
903 
904 // Determine whether the two operations are the same except that pointer-to-A
905 // and pointer-to-B are equivalent. This should be kept in sync with
906 // Instruction::isSameOperationAs.
907 // Read method declaration comments for more details.
908 int FunctionComparator::cmpOperations(const Instruction *L,
909                                       const Instruction *R) const {
910   // Differences from Instruction::isSameOperationAs:
911   //  * replace type comparison with calls to cmpTypes.
912   //  * we test for I->getRawSubclassOptionalData (nuw/nsw/tail) at the top.
913   //  * because of the above, we don't test for the tail bit on calls later on.
914   if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
915     return Res;
916 
917   if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
918     return Res;
919 
920   if (int Res = cmpTypes(L->getType(), R->getType()))
921     return Res;
922 
923   if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
924                            R->getRawSubclassOptionalData()))
925     return Res;
926 
927   // We have two instructions of identical opcode and #operands.  Check to see
928   // if all operands are the same type
929   for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
930     if (int Res =
931             cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
932       return Res;
933   }
934 
935   // Check special state that is a part of some instructions.
936   if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
937     if (int Res = cmpTypes(AI->getAllocatedType(),
938                            cast<AllocaInst>(R)->getAllocatedType()))
939       return Res;
940     return cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment());
941   }
942   if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
943     if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
944       return Res;
945     if (int Res =
946             cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
947       return Res;
948     if (int Res =
949             cmpOrderings(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
950       return Res;
951     if (int Res =
952             cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
953       return Res;
954     return cmpRangeMetadata(LI->getMetadata(LLVMContext::MD_range),
955         cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
956   }
957   if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
958     if (int Res =
959             cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
960       return Res;
961     if (int Res =
962             cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
963       return Res;
964     if (int Res =
965             cmpOrderings(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
966       return Res;
967     return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
968   }
969   if (const CmpInst *CI = dyn_cast<CmpInst>(L))
970     return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
971   if (const CallInst *CI = dyn_cast<CallInst>(L)) {
972     if (int Res = cmpNumbers(CI->getCallingConv(),
973                              cast<CallInst>(R)->getCallingConv()))
974       return Res;
975     if (int Res =
976             cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
977       return Res;
978     if (int Res = cmpOperandBundlesSchema(CI, R))
979       return Res;
980     return cmpRangeMetadata(
981         CI->getMetadata(LLVMContext::MD_range),
982         cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
983   }
984   if (const InvokeInst *II = dyn_cast<InvokeInst>(L)) {
985     if (int Res = cmpNumbers(II->getCallingConv(),
986                              cast<InvokeInst>(R)->getCallingConv()))
987       return Res;
988     if (int Res =
989             cmpAttrs(II->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
990       return Res;
991     if (int Res = cmpOperandBundlesSchema(II, R))
992       return Res;
993     return cmpRangeMetadata(
994         II->getMetadata(LLVMContext::MD_range),
995         cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
996   }
997   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
998     ArrayRef<unsigned> LIndices = IVI->getIndices();
999     ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
1000     if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
1001       return Res;
1002     for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
1003       if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
1004         return Res;
1005     }
1006     return 0;
1007   }
1008   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
1009     ArrayRef<unsigned> LIndices = EVI->getIndices();
1010     ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
1011     if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
1012       return Res;
1013     for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
1014       if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
1015         return Res;
1016     }
1017   }
1018   if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
1019     if (int Res =
1020             cmpOrderings(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
1021       return Res;
1022     return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
1023   }
1024   if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
1025     if (int Res = cmpNumbers(CXI->isVolatile(),
1026                              cast<AtomicCmpXchgInst>(R)->isVolatile()))
1027       return Res;
1028     if (int Res = cmpNumbers(CXI->isWeak(),
1029                              cast<AtomicCmpXchgInst>(R)->isWeak()))
1030       return Res;
1031     if (int Res =
1032             cmpOrderings(CXI->getSuccessOrdering(),
1033                          cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
1034       return Res;
1035     if (int Res =
1036             cmpOrderings(CXI->getFailureOrdering(),
1037                          cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
1038       return Res;
1039     return cmpNumbers(CXI->getSynchScope(),
1040                       cast<AtomicCmpXchgInst>(R)->getSynchScope());
1041   }
1042   if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
1043     if (int Res = cmpNumbers(RMWI->getOperation(),
1044                              cast<AtomicRMWInst>(R)->getOperation()))
1045       return Res;
1046     if (int Res = cmpNumbers(RMWI->isVolatile(),
1047                              cast<AtomicRMWInst>(R)->isVolatile()))
1048       return Res;
1049     if (int Res = cmpOrderings(RMWI->getOrdering(),
1050                              cast<AtomicRMWInst>(R)->getOrdering()))
1051       return Res;
1052     return cmpNumbers(RMWI->getSynchScope(),
1053                       cast<AtomicRMWInst>(R)->getSynchScope());
1054   }
1055   return 0;
1056 }
1057 
1058 // Determine whether two GEP operations perform the same underlying arithmetic.
1059 // Read method declaration comments for more details.
1060 int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
1061                                 const GEPOperator *GEPR) const {
1062 
1063   unsigned int ASL = GEPL->getPointerAddressSpace();
1064   unsigned int ASR = GEPR->getPointerAddressSpace();
1065 
1066   if (int Res = cmpNumbers(ASL, ASR))
1067     return Res;
1068 
1069   // When we have target data, we can reduce the GEP down to the value in bytes
1070   // added to the address.
1071   const DataLayout &DL = FnL->getParent()->getDataLayout();
1072   unsigned BitWidth = DL.getPointerSizeInBits(ASL);
1073   APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
1074   if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
1075       GEPR->accumulateConstantOffset(DL, OffsetR))
1076     return cmpAPInts(OffsetL, OffsetR);
1077   if (int Res = cmpTypes(GEPL->getSourceElementType(),
1078                          GEPR->getSourceElementType()))
1079     return Res;
1080 
1081   if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
1082     return Res;
1083 
1084   for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
1085     if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
1086       return Res;
1087   }
1088 
1089   return 0;
1090 }
1091 
1092 int FunctionComparator::cmpInlineAsm(const InlineAsm *L,
1093                                      const InlineAsm *R) const {
1094   // InlineAsm's are uniqued. If they are the same pointer, obviously they are
1095   // the same, otherwise compare the fields.
1096   if (L == R)
1097     return 0;
1098   if (int Res = cmpTypes(L->getFunctionType(), R->getFunctionType()))
1099     return Res;
1100   if (int Res = cmpMem(L->getAsmString(), R->getAsmString()))
1101     return Res;
1102   if (int Res = cmpMem(L->getConstraintString(), R->getConstraintString()))
1103     return Res;
1104   if (int Res = cmpNumbers(L->hasSideEffects(), R->hasSideEffects()))
1105     return Res;
1106   if (int Res = cmpNumbers(L->isAlignStack(), R->isAlignStack()))
1107     return Res;
1108   if (int Res = cmpNumbers(L->getDialect(), R->getDialect()))
1109     return Res;
1110   llvm_unreachable("InlineAsm blocks were not uniqued.");
1111   return 0;
1112 }
1113 
1114 /// Compare two values used by the two functions under pair-wise comparison. If
1115 /// this is the first time the values are seen, they're added to the mapping so
1116 /// that we will detect mismatches on next use.
1117 /// See comments in declaration for more details.
1118 int FunctionComparator::cmpValues(const Value *L, const Value *R) const {
1119   // Catch self-reference case.
1120   if (L == FnL) {
1121     if (R == FnR)
1122       return 0;
1123     return -1;
1124   }
1125   if (R == FnR) {
1126     if (L == FnL)
1127       return 0;
1128     return 1;
1129   }
1130 
1131   const Constant *ConstL = dyn_cast<Constant>(L);
1132   const Constant *ConstR = dyn_cast<Constant>(R);
1133   if (ConstL && ConstR) {
1134     if (L == R)
1135       return 0;
1136     return cmpConstants(ConstL, ConstR);
1137   }
1138 
1139   if (ConstL)
1140     return 1;
1141   if (ConstR)
1142     return -1;
1143 
1144   const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
1145   const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
1146 
1147   if (InlineAsmL && InlineAsmR)
1148     return cmpInlineAsm(InlineAsmL, InlineAsmR);
1149   if (InlineAsmL)
1150     return 1;
1151   if (InlineAsmR)
1152     return -1;
1153 
1154   auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
1155        RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
1156 
1157   return cmpNumbers(LeftSN.first->second, RightSN.first->second);
1158 }
1159 // Test whether two basic blocks have equivalent behaviour.
1160 int FunctionComparator::cmpBasicBlocks(const BasicBlock *BBL,
1161                                        const BasicBlock *BBR) const {
1162   BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
1163   BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
1164 
1165   do {
1166     if (int Res = cmpValues(&*InstL, &*InstR))
1167       return Res;
1168 
1169     const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
1170     const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
1171 
1172     if (GEPL && !GEPR)
1173       return 1;
1174     if (GEPR && !GEPL)
1175       return -1;
1176 
1177     if (GEPL && GEPR) {
1178       if (int Res =
1179               cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
1180         return Res;
1181       if (int Res = cmpGEPs(GEPL, GEPR))
1182         return Res;
1183     } else {
1184       if (int Res = cmpOperations(&*InstL, &*InstR))
1185         return Res;
1186       assert(InstL->getNumOperands() == InstR->getNumOperands());
1187 
1188       for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
1189         Value *OpL = InstL->getOperand(i);
1190         Value *OpR = InstR->getOperand(i);
1191         if (int Res = cmpValues(OpL, OpR))
1192           return Res;
1193         // cmpValues should ensure this is true.
1194         assert(cmpTypes(OpL->getType(), OpR->getType()) == 0);
1195       }
1196     }
1197 
1198     ++InstL;
1199     ++InstR;
1200   } while (InstL != InstLE && InstR != InstRE);
1201 
1202   if (InstL != InstLE && InstR == InstRE)
1203     return 1;
1204   if (InstL == InstLE && InstR != InstRE)
1205     return -1;
1206   return 0;
1207 }
1208 
1209 // Test whether the two functions have equivalent behaviour.
1210 int FunctionComparator::compare() {
1211   sn_mapL.clear();
1212   sn_mapR.clear();
1213 
1214   if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1215     return Res;
1216 
1217   if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1218     return Res;
1219 
1220   if (FnL->hasGC()) {
1221     if (int Res = cmpMem(FnL->getGC(), FnR->getGC()))
1222       return Res;
1223   }
1224 
1225   if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1226     return Res;
1227 
1228   if (FnL->hasSection()) {
1229     if (int Res = cmpMem(FnL->getSection(), FnR->getSection()))
1230       return Res;
1231   }
1232 
1233   if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1234     return Res;
1235 
1236   // TODO: if it's internal and only used in direct calls, we could handle this
1237   // case too.
1238   if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1239     return Res;
1240 
1241   if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
1242     return Res;
1243 
1244   assert(FnL->arg_size() == FnR->arg_size() &&
1245          "Identically typed functions have different numbers of args!");
1246 
1247   // Visit the arguments so that they get enumerated in the order they're
1248   // passed in.
1249   for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1250                                     ArgRI = FnR->arg_begin(),
1251                                     ArgLE = FnL->arg_end();
1252        ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1253     if (cmpValues(&*ArgLI, &*ArgRI) != 0)
1254       llvm_unreachable("Arguments repeat!");
1255   }
1256 
1257   // We do a CFG-ordered walk since the actual ordering of the blocks in the
1258   // linked list is immaterial. Our walk starts at the entry block for both
1259   // functions, then takes each block from each terminator in order. As an
1260   // artifact, this also means that unreachable blocks are ignored.
1261   SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
1262   SmallPtrSet<const BasicBlock *, 32> VisitedBBs; // in terms of F1.
1263 
1264   FnLBBs.push_back(&FnL->getEntryBlock());
1265   FnRBBs.push_back(&FnR->getEntryBlock());
1266 
1267   VisitedBBs.insert(FnLBBs[0]);
1268   while (!FnLBBs.empty()) {
1269     const BasicBlock *BBL = FnLBBs.pop_back_val();
1270     const BasicBlock *BBR = FnRBBs.pop_back_val();
1271 
1272     if (int Res = cmpValues(BBL, BBR))
1273       return Res;
1274 
1275     if (int Res = cmpBasicBlocks(BBL, BBR))
1276       return Res;
1277 
1278     const TerminatorInst *TermL = BBL->getTerminator();
1279     const TerminatorInst *TermR = BBR->getTerminator();
1280 
1281     assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1282     for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
1283       if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
1284         continue;
1285 
1286       FnLBBs.push_back(TermL->getSuccessor(i));
1287       FnRBBs.push_back(TermR->getSuccessor(i));
1288     }
1289   }
1290   return 0;
1291 }
1292 
1293 namespace {
1294 // Accumulate the hash of a sequence of 64-bit integers. This is similar to a
1295 // hash of a sequence of 64bit ints, but the entire input does not need to be
1296 // available at once. This interface is necessary for functionHash because it
1297 // needs to accumulate the hash as the structure of the function is traversed
1298 // without saving these values to an intermediate buffer. This form of hashing
1299 // is not often needed, as usually the object to hash is just read from a
1300 // buffer.
1301 class HashAccumulator64 {
1302   uint64_t Hash;
1303 public:
1304   // Initialize to random constant, so the state isn't zero.
1305   HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
1306   void add(uint64_t V) {
1307      Hash = llvm::hashing::detail::hash_16_bytes(Hash, V);
1308   }
1309   // No finishing is required, because the entire hash value is used.
1310   uint64_t getHash() { return Hash; }
1311 };
1312 } // end anonymous namespace
1313 
1314 // A function hash is calculated by considering only the number of arguments and
1315 // whether a function is varargs, the order of basic blocks (given by the
1316 // successors of each basic block in depth first order), and the order of
1317 // opcodes of each instruction within each of these basic blocks. This mirrors
1318 // the strategy compare() uses to compare functions by walking the BBs in depth
1319 // first order and comparing each instruction in sequence. Because this hash
1320 // does not look at the operands, it is insensitive to things such as the
1321 // target of calls and the constants used in the function, which makes it useful
1322 // when possibly merging functions which are the same modulo constants and call
1323 // targets.
1324 FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
1325   HashAccumulator64 H;
1326   H.add(F.isVarArg());
1327   H.add(F.arg_size());
1328 
1329   SmallVector<const BasicBlock *, 8> BBs;
1330   SmallSet<const BasicBlock *, 16> VisitedBBs;
1331 
1332   // Walk the blocks in the same order as FunctionComparator::cmpBasicBlocks(),
1333   // accumulating the hash of the function "structure." (BB and opcode sequence)
1334   BBs.push_back(&F.getEntryBlock());
1335   VisitedBBs.insert(BBs[0]);
1336   while (!BBs.empty()) {
1337     const BasicBlock *BB = BBs.pop_back_val();
1338     // This random value acts as a block header, as otherwise the partition of
1339     // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
1340     H.add(45798);
1341     for (auto &Inst : *BB) {
1342       H.add(Inst.getOpcode());
1343     }
1344     const TerminatorInst *Term = BB->getTerminator();
1345     for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
1346       if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
1347         continue;
1348       BBs.push_back(Term->getSuccessor(i));
1349     }
1350   }
1351   return H.getHash();
1352 }
1353 
1354 
1355 namespace {
1356 
1357 /// MergeFunctions finds functions which will generate identical machine code,
1358 /// by considering all pointer types to be equivalent. Once identified,
1359 /// MergeFunctions will fold them by replacing a call to one to a call to a
1360 /// bitcast of the other.
1361 ///
1362 class MergeFunctions : public ModulePass {
1363 public:
1364   static char ID;
1365   MergeFunctions()
1366     : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)), FNodesInTree(),
1367       HasGlobalAliases(false) {
1368     initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1369   }
1370 
1371   bool runOnModule(Module &M) override;
1372 
1373 private:
1374   // The function comparison operator is provided here so that FunctionNodes do
1375   // not need to become larger with another pointer.
1376   class FunctionNodeCmp {
1377     GlobalNumberState* GlobalNumbers;
1378   public:
1379     FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
1380     bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
1381       // Order first by hashes, then full function comparison.
1382       if (LHS.getHash() != RHS.getHash())
1383         return LHS.getHash() < RHS.getHash();
1384       FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
1385       return FCmp.compare() == -1;
1386     }
1387   };
1388   typedef std::set<FunctionNode, FunctionNodeCmp> FnTreeType;
1389 
1390   GlobalNumberState GlobalNumbers;
1391 
1392   /// A work queue of functions that may have been modified and should be
1393   /// analyzed again.
1394   std::vector<WeakVH> Deferred;
1395 
1396   /// Checks the rules of order relation introduced among functions set.
1397   /// Returns true, if sanity check has been passed, and false if failed.
1398   bool doSanityCheck(std::vector<WeakVH> &Worklist);
1399 
1400   /// Insert a ComparableFunction into the FnTree, or merge it away if it's
1401   /// equal to one that's already present.
1402   bool insert(Function *NewFunction);
1403 
1404   /// Remove a Function from the FnTree and queue it up for a second sweep of
1405   /// analysis.
1406   void remove(Function *F);
1407 
1408   /// Find the functions that use this Value and remove them from FnTree and
1409   /// queue the functions.
1410   void removeUsers(Value *V);
1411 
1412   /// Replace all direct calls of Old with calls of New. Will bitcast New if
1413   /// necessary to make types match.
1414   void replaceDirectCallers(Function *Old, Function *New);
1415 
1416   /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1417   /// be converted into a thunk. In either case, it should never be visited
1418   /// again.
1419   void mergeTwoFunctions(Function *F, Function *G);
1420 
1421   /// Replace G with a thunk or an alias to F. Deletes G.
1422   void writeThunkOrAlias(Function *F, Function *G);
1423 
1424   /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1425   /// of G with bitcast(F). Deletes G.
1426   void writeThunk(Function *F, Function *G);
1427 
1428   /// Replace G with an alias to F. Deletes G.
1429   void writeAlias(Function *F, Function *G);
1430 
1431   /// Replace function F with function G in the function tree.
1432   void replaceFunctionInTree(const FunctionNode &FN, Function *G);
1433 
1434   /// The set of all distinct functions. Use the insert() and remove() methods
1435   /// to modify it. The map allows efficient lookup and deferring of Functions.
1436   FnTreeType FnTree;
1437   // Map functions to the iterators of the FunctionNode which contains them
1438   // in the FnTree. This must be updated carefully whenever the FnTree is
1439   // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
1440   // dangling iterators into FnTree. The invariant that preserves this is that
1441   // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
1442   ValueMap<Function*, FnTreeType::iterator> FNodesInTree;
1443 
1444   /// Whether or not the target supports global aliases.
1445   bool HasGlobalAliases;
1446 };
1447 
1448 } // end anonymous namespace
1449 
1450 char MergeFunctions::ID = 0;
1451 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1452 
1453 ModulePass *llvm::createMergeFunctionsPass() {
1454   return new MergeFunctions();
1455 }
1456 
1457 bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1458   if (const unsigned Max = NumFunctionsForSanityCheck) {
1459     unsigned TripleNumber = 0;
1460     bool Valid = true;
1461 
1462     dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1463 
1464     unsigned i = 0;
1465     for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1466          I != E && i < Max; ++I, ++i) {
1467       unsigned j = i;
1468       for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1469         Function *F1 = cast<Function>(*I);
1470         Function *F2 = cast<Function>(*J);
1471         int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
1472         int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
1473 
1474         // If F1 <= F2, then F2 >= F1, otherwise report failure.
1475         if (Res1 != -Res2) {
1476           dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1477                  << "\n";
1478           F1->dump();
1479           F2->dump();
1480           Valid = false;
1481         }
1482 
1483         if (Res1 == 0)
1484           continue;
1485 
1486         unsigned k = j;
1487         for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1488              ++k, ++K, ++TripleNumber) {
1489           if (K == J)
1490             continue;
1491 
1492           Function *F3 = cast<Function>(*K);
1493           int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
1494           int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
1495 
1496           bool Transitive = true;
1497 
1498           if (Res1 != 0 && Res1 == Res4) {
1499             // F1 > F2, F2 > F3 => F1 > F3
1500             Transitive = Res3 == Res1;
1501           } else if (Res3 != 0 && Res3 == -Res4) {
1502             // F1 > F3, F3 > F2 => F1 > F2
1503             Transitive = Res3 == Res1;
1504           } else if (Res4 != 0 && -Res3 == Res4) {
1505             // F2 > F3, F3 > F1 => F2 > F1
1506             Transitive = Res4 == -Res1;
1507           }
1508 
1509           if (!Transitive) {
1510             dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1511                    << TripleNumber << "\n";
1512             dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1513                    << Res4 << "\n";
1514             F1->dump();
1515             F2->dump();
1516             F3->dump();
1517             Valid = false;
1518           }
1519         }
1520       }
1521     }
1522 
1523     dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1524     return Valid;
1525   }
1526   return true;
1527 }
1528 
1529 bool MergeFunctions::runOnModule(Module &M) {
1530   bool Changed = false;
1531 
1532   // All functions in the module, ordered by hash. Functions with a unique
1533   // hash value are easily eliminated.
1534   std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
1535     HashedFuncs;
1536   for (Function &Func : M) {
1537     if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
1538       HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
1539     }
1540   }
1541 
1542   std::stable_sort(
1543       HashedFuncs.begin(), HashedFuncs.end(),
1544       [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
1545          const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
1546         return a.first < b.first;
1547       });
1548 
1549   auto S = HashedFuncs.begin();
1550   for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
1551     // If the hash value matches the previous value or the next one, we must
1552     // consider merging it. Otherwise it is dropped and never considered again.
1553     if ((I != S && std::prev(I)->first == I->first) ||
1554         (std::next(I) != IE && std::next(I)->first == I->first) ) {
1555       Deferred.push_back(WeakVH(I->second));
1556     }
1557   }
1558 
1559   do {
1560     std::vector<WeakVH> Worklist;
1561     Deferred.swap(Worklist);
1562 
1563     DEBUG(doSanityCheck(Worklist));
1564 
1565     DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1566     DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1567 
1568     // Insert only strong functions and merge them. Strong function merging
1569     // always deletes one of them.
1570     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1571            E = Worklist.end(); I != E; ++I) {
1572       if (!*I) continue;
1573       Function *F = cast<Function>(*I);
1574       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1575           !F->isInterposable()) {
1576         Changed |= insert(F);
1577       }
1578     }
1579 
1580     // Insert only weak functions and merge them. By doing these second we
1581     // create thunks to the strong function when possible. When two weak
1582     // functions are identical, we create a new strong function with two weak
1583     // weak thunks to it which are identical but not mergable.
1584     for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1585            E = Worklist.end(); I != E; ++I) {
1586       if (!*I) continue;
1587       Function *F = cast<Function>(*I);
1588       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1589           F->isInterposable()) {
1590         Changed |= insert(F);
1591       }
1592     }
1593     DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
1594   } while (!Deferred.empty());
1595 
1596   FnTree.clear();
1597   GlobalNumbers.clear();
1598 
1599   return Changed;
1600 }
1601 
1602 // Replace direct callers of Old with New.
1603 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1604   Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
1605   for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1606     Use *U = &*UI;
1607     ++UI;
1608     CallSite CS(U->getUser());
1609     if (CS && CS.isCallee(U)) {
1610       // Transfer the called function's attributes to the call site. Due to the
1611       // bitcast we will 'lose' ABI changing attributes because the 'called
1612       // function' is no longer a Function* but the bitcast. Code that looks up
1613       // the attributes from the called function will fail.
1614 
1615       // FIXME: This is not actually true, at least not anymore. The callsite
1616       // will always have the same ABI affecting attributes as the callee,
1617       // because otherwise the original input has UB. Note that Old and New
1618       // always have matching ABI, so no attributes need to be changed.
1619       // Transferring other attributes may help other optimizations, but that
1620       // should be done uniformly and not in this ad-hoc way.
1621       auto &Context = New->getContext();
1622       auto NewFuncAttrs = New->getAttributes();
1623       auto CallSiteAttrs = CS.getAttributes();
1624 
1625       CallSiteAttrs = CallSiteAttrs.addAttributes(
1626           Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes());
1627 
1628       for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) {
1629         AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx);
1630         if (Attrs.getNumSlots())
1631           CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs);
1632       }
1633 
1634       CS.setAttributes(CallSiteAttrs);
1635 
1636       remove(CS.getInstruction()->getParent()->getParent());
1637       U->set(BitcastNew);
1638     }
1639   }
1640 }
1641 
1642 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1643 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
1644   if (HasGlobalAliases && G->hasUnnamedAddr()) {
1645     if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1646         G->hasWeakLinkage()) {
1647       writeAlias(F, G);
1648       return;
1649     }
1650   }
1651 
1652   writeThunk(F, G);
1653 }
1654 
1655 // Helper for writeThunk,
1656 // Selects proper bitcast operation,
1657 // but a bit simpler then CastInst::getCastOpcode.
1658 static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
1659   Type *SrcTy = V->getType();
1660   if (SrcTy->isStructTy()) {
1661     assert(DestTy->isStructTy());
1662     assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1663     Value *Result = UndefValue::get(DestTy);
1664     for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1665       Value *Element = createCast(
1666           Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
1667           DestTy->getStructElementType(I));
1668 
1669       Result =
1670           Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
1671     }
1672     return Result;
1673   }
1674   assert(!DestTy->isStructTy());
1675   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1676     return Builder.CreateIntToPtr(V, DestTy);
1677   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1678     return Builder.CreatePtrToInt(V, DestTy);
1679   else
1680     return Builder.CreateBitCast(V, DestTy);
1681 }
1682 
1683 // Replace G with a simple tail call to bitcast(F). Also replace direct uses
1684 // of G with bitcast(F). Deletes G.
1685 void MergeFunctions::writeThunk(Function *F, Function *G) {
1686   if (!G->isInterposable()) {
1687     // Redirect direct callers of G to F.
1688     replaceDirectCallers(G, F);
1689   }
1690 
1691   // If G was internal then we may have replaced all uses of G with F. If so,
1692   // stop here and delete G. There's no need for a thunk.
1693   if (G->hasLocalLinkage() && G->use_empty()) {
1694     G->eraseFromParent();
1695     return;
1696   }
1697 
1698   Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1699                                     G->getParent());
1700   BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
1701   IRBuilder<> Builder(BB);
1702 
1703   SmallVector<Value *, 16> Args;
1704   unsigned i = 0;
1705   FunctionType *FFTy = F->getFunctionType();
1706   for (Argument & AI : NewG->args()) {
1707     Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
1708     ++i;
1709   }
1710 
1711   CallInst *CI = Builder.CreateCall(F, Args);
1712   CI->setTailCall();
1713   CI->setCallingConv(F->getCallingConv());
1714   CI->setAttributes(F->getAttributes());
1715   if (NewG->getReturnType()->isVoidTy()) {
1716     Builder.CreateRetVoid();
1717   } else {
1718     Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
1719   }
1720 
1721   NewG->copyAttributesFrom(G);
1722   NewG->takeName(G);
1723   removeUsers(G);
1724   G->replaceAllUsesWith(NewG);
1725   G->eraseFromParent();
1726 
1727   DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
1728   ++NumThunksWritten;
1729 }
1730 
1731 // Replace G with an alias to F and delete G.
1732 void MergeFunctions::writeAlias(Function *F, Function *G) {
1733   auto *GA = GlobalAlias::create(G->getLinkage(), "", F);
1734   F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1735   GA->takeName(G);
1736   GA->setVisibility(G->getVisibility());
1737   removeUsers(G);
1738   G->replaceAllUsesWith(GA);
1739   G->eraseFromParent();
1740 
1741   DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
1742   ++NumAliasesWritten;
1743 }
1744 
1745 // Merge two equivalent functions. Upon completion, Function G is deleted.
1746 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
1747   if (F->isInterposable()) {
1748     assert(G->isInterposable());
1749 
1750     // Make them both thunks to the same internal function.
1751     Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1752                                    F->getParent());
1753     H->copyAttributesFrom(F);
1754     H->takeName(F);
1755     removeUsers(F);
1756     F->replaceAllUsesWith(H);
1757 
1758     unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1759 
1760     if (HasGlobalAliases) {
1761       writeAlias(F, G);
1762       writeAlias(F, H);
1763     } else {
1764       writeThunk(F, G);
1765       writeThunk(F, H);
1766     }
1767 
1768     F->setAlignment(MaxAlignment);
1769     F->setLinkage(GlobalValue::PrivateLinkage);
1770     ++NumDoubleWeak;
1771   } else {
1772     writeThunkOrAlias(F, G);
1773   }
1774 
1775   ++NumFunctionsMerged;
1776 }
1777 
1778 /// Replace function F by function G.
1779 void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
1780                                            Function *G) {
1781   Function *F = FN.getFunc();
1782   assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
1783          "The two functions must be equal");
1784 
1785   auto I = FNodesInTree.find(F);
1786   assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
1787   assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
1788 
1789   FnTreeType::iterator IterToFNInFnTree = I->second;
1790   assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
1791   // Remove F -> FN and insert G -> FN
1792   FNodesInTree.erase(I);
1793   FNodesInTree.insert({G, IterToFNInFnTree});
1794   // Replace F with G in FN, which is stored inside the FnTree.
1795   FN.replaceBy(G);
1796 }
1797 
1798 // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
1799 // that was already inserted.
1800 bool MergeFunctions::insert(Function *NewFunction) {
1801   std::pair<FnTreeType::iterator, bool> Result =
1802       FnTree.insert(FunctionNode(NewFunction));
1803 
1804   if (Result.second) {
1805     assert(FNodesInTree.count(NewFunction) == 0);
1806     FNodesInTree.insert({NewFunction, Result.first});
1807     DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
1808     return false;
1809   }
1810 
1811   const FunctionNode &OldF = *Result.first;
1812 
1813   // Don't merge tiny functions, since it can just end up making the function
1814   // larger.
1815   // FIXME: Should still merge them if they are unnamed_addr and produce an
1816   // alias.
1817   if (NewFunction->size() == 1) {
1818     if (NewFunction->front().size() <= 2) {
1819       DEBUG(dbgs() << NewFunction->getName()
1820                    << " is to small to bother merging\n");
1821       return false;
1822     }
1823   }
1824 
1825   // Impose a total order (by name) on the replacement of functions. This is
1826   // important when operating on more than one module independently to prevent
1827   // cycles of thunks calling each other when the modules are linked together.
1828   //
1829   // When one function is weak and the other is strong there is an order imposed
1830   // already. We process strong functions before weak functions.
1831   if ((OldF.getFunc()->isInterposable() && NewFunction->isInterposable()) ||
1832       (!OldF.getFunc()->isInterposable() && !NewFunction->isInterposable()))
1833     if (OldF.getFunc()->getName() > NewFunction->getName()) {
1834       // Swap the two functions.
1835       Function *F = OldF.getFunc();
1836       replaceFunctionInTree(*Result.first, NewFunction);
1837       NewFunction = F;
1838       assert(OldF.getFunc() != F && "Must have swapped the functions.");
1839     }
1840 
1841   // Never thunk a strong function to a weak function.
1842   assert(!OldF.getFunc()->isInterposable() || NewFunction->isInterposable());
1843 
1844   DEBUG(dbgs() << "  " << OldF.getFunc()->getName()
1845                << " == " << NewFunction->getName() << '\n');
1846 
1847   Function *DeleteF = NewFunction;
1848   mergeTwoFunctions(OldF.getFunc(), DeleteF);
1849   return true;
1850 }
1851 
1852 // Remove a function from FnTree. If it was already in FnTree, add
1853 // it to Deferred so that we'll look at it in the next round.
1854 void MergeFunctions::remove(Function *F) {
1855   auto I = FNodesInTree.find(F);
1856   if (I != FNodesInTree.end()) {
1857     DEBUG(dbgs() << "Deferred " << F->getName()<< ".\n");
1858     FnTree.erase(I->second);
1859     // I->second has been invalidated, remove it from the FNodesInTree map to
1860     // preserve the invariant.
1861     FNodesInTree.erase(I);
1862     Deferred.emplace_back(F);
1863   }
1864 }
1865 
1866 // For each instruction used by the value, remove() the function that contains
1867 // the instruction. This should happen right before a call to RAUW.
1868 void MergeFunctions::removeUsers(Value *V) {
1869   std::vector<Value *> Worklist;
1870   Worklist.push_back(V);
1871   SmallSet<Value*, 8> Visited;
1872   Visited.insert(V);
1873   while (!Worklist.empty()) {
1874     Value *V = Worklist.back();
1875     Worklist.pop_back();
1876 
1877     for (User *U : V->users()) {
1878       if (Instruction *I = dyn_cast<Instruction>(U)) {
1879         remove(I->getParent()->getParent());
1880       } else if (isa<GlobalValue>(U)) {
1881         // do nothing
1882       } else if (Constant *C = dyn_cast<Constant>(U)) {
1883         for (User *UU : C->users()) {
1884           if (!Visited.insert(UU).second)
1885             Worklist.push_back(UU);
1886         }
1887       }
1888     }
1889   }
1890 }
1891