1 //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass looks for equivalent functions that are mergable and folds them.
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).
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.
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.
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.
43 //===----------------------------------------------------------------------===//
47 // * virtual functions.
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.
53 // * be smarter about bitcasts.
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.
60 // * Compare complex types with pointer types inside.
61 // * Compare cross-reference cases.
62 // * Compare complex expressions.
64 // All the three issues above could be described as ability to prove that
65 // fA == fB == fC == fE == fF == fG in example below:
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.
90 //===----------------------------------------------------------------------===//
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/Pass.h"
110 #include "llvm/Support/CommandLine.h"
111 #include "llvm/Support/Debug.h"
112 #include "llvm/Support/ErrorHandling.h"
113 #include "llvm/Support/raw_ostream.h"
115 using namespace llvm;
117 #define DEBUG_TYPE "mergefunc"
119 STATISTIC(NumFunctionsMerged, "Number of functions merged");
120 STATISTIC(NumThunksWritten, "Number of thunks generated");
121 STATISTIC(NumAliasesWritten, "Number of aliases generated");
122 STATISTIC(NumDoubleWeak, "Number of new functions created");
124 static cl::opt<unsigned> NumFunctionsForSanityCheck(
126 cl::desc("How many functions in module could be used for "
127 "MergeFunctions pass sanity check. "
128 "'0' disables this check. Works only with '-debug' key."),
129 cl::init(0), cl::Hidden);
133 /// FunctionComparator - Compares two functions to determine whether or not
134 /// they will generate machine code with the same behaviour. DataLayout is
135 /// used if available. The comparator always fails conservatively (erring on the
136 /// side of claiming that two functions are different).
137 class FunctionComparator {
139 FunctionComparator(const Function *F1, const Function *F2)
140 : FnL(F1), FnR(F2) {}
142 /// Test whether the two functions have equivalent behaviour.
144 /// Hash a function. Equivalent functions will have the same hash, and unequal
145 /// functions will have different hashes with high probability.
146 typedef uint64_t FunctionHash;
147 static FunctionHash functionHash(Function &);
150 /// Test whether two basic blocks have equivalent behaviour.
151 int compare(const BasicBlock *BBL, const BasicBlock *BBR);
153 /// Constants comparison.
154 /// Its analog to lexicographical comparison between hypothetical numbers
156 /// <bitcastability-trait><raw-bit-contents>
158 /// 1. Bitcastability.
159 /// Check whether L's type could be losslessly bitcasted to R's type.
160 /// On this stage method, in case when lossless bitcast is not possible
161 /// method returns -1 or 1, thus also defining which type is greater in
162 /// context of bitcastability.
163 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
164 /// to the contents comparison.
165 /// If types differ, remember types comparison result and check
166 /// whether we still can bitcast types.
167 /// Stage 1: Types that satisfies isFirstClassType conditions are always
168 /// greater then others.
169 /// Stage 2: Vector is greater then non-vector.
170 /// If both types are vectors, then vector with greater bitwidth is
172 /// If both types are vectors with the same bitwidth, then types
173 /// are bitcastable, and we can skip other stages, and go to contents
175 /// Stage 3: Pointer types are greater than non-pointers. If both types are
176 /// pointers of the same address space - go to contents comparison.
177 /// Different address spaces: pointer with greater address space is
179 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
180 /// We don't know how to bitcast them. So, we better don't do it,
181 /// and return types comparison result (so it determines the
182 /// relationship among constants we don't know how to bitcast).
184 /// Just for clearance, let's see how the set of constants could look
185 /// on single dimension axis:
187 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
188 /// Where: NFCT - Not a FirstClassType
189 /// FCT - FirstClassTyp:
191 /// 2. Compare raw contents.
192 /// It ignores types on this stage and only compares bits from L and R.
193 /// Returns 0, if L and R has equivalent contents.
194 /// -1 or 1 if values are different.
196 /// 2.1. If contents are numbers, compare numbers.
197 /// Ints with greater bitwidth are greater. Ints with same bitwidths
198 /// compared by their contents.
199 /// 2.2. "And so on". Just to avoid discrepancies with comments
200 /// perhaps it would be better to read the implementation itself.
201 /// 3. And again about overall picture. Let's look back at how the ordered set
202 /// of constants will look like:
203 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
205 /// Now look, what could be inside [FCT, "others"], for example:
206 /// [FCT, "others"] =
208 /// [double 0.1], [double 1.23],
209 /// [i32 1], [i32 2],
210 /// { double 1.0 }, ; StructTyID, NumElements = 1
211 /// { i32 1 }, ; StructTyID, NumElements = 1
212 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
213 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
216 /// Let's explain the order. Float numbers will be less than integers, just
217 /// because of cmpType terms: FloatTyID < IntegerTyID.
218 /// Floats (with same fltSemantics) are sorted according to their value.
219 /// Then you can see integers, and they are, like a floats,
220 /// could be easy sorted among each others.
221 /// The structures. Structures are grouped at the tail, again because of their
222 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
223 /// Structures with greater number of elements are greater. Structures with
224 /// greater elements going first are greater.
225 /// The same logic with vectors, arrays and other possible complex types.
227 /// Bitcastable constants.
228 /// Let's assume, that some constant, belongs to some group of
229 /// "so-called-equal" values with different types, and at the same time
230 /// belongs to another group of constants with equal types
231 /// and "really" equal values.
233 /// Now, prove that this is impossible:
235 /// If constant A with type TyA is bitcastable to B with type TyB, then:
236 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
237 /// those should be vectors (if TyA is vector), pointers
238 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
240 /// 2. All constants with non-equal, but bitcastable types to TyA, are
241 /// bitcastable to B.
242 /// Once again, just because we allow it to vectors and pointers only.
243 /// This statement could be expanded as below:
244 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
245 /// vector B, and thus bitcastable to B as well.
246 /// 2.2. All pointers of the same address space, no matter what they point to,
247 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
248 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
251 /// In another words, for pointers and vectors, we ignore top-level type and
252 /// look at their particular properties (bit-width for vectors, and
253 /// address space for pointers).
254 /// If these properties are equal - compare their contents.
255 int cmpConstants(const Constant *L, const Constant *R);
257 /// Assign or look up previously assigned numbers for the two values, and
258 /// return whether the numbers are equal. Numbers are assigned in the order
260 /// Comparison order:
261 /// Stage 0: Value that is function itself is always greater then others.
262 /// If left and right values are references to their functions, then
264 /// Stage 1: Constants are greater than non-constants.
265 /// If both left and right are constants, then the result of
266 /// cmpConstants is used as cmpValues result.
267 /// Stage 2: InlineAsm instances are greater than others. If both left and
268 /// right are InlineAsm instances, InlineAsm* pointers casted to
269 /// integers and compared as numbers.
270 /// Stage 3: For all other cases we compare order we meet these values in
271 /// their functions. If right value was met first during scanning,
272 /// then left value is greater.
273 /// In another words, we compare serial numbers, for more details
274 /// see comments for sn_mapL and sn_mapR.
275 int cmpValues(const Value *L, const Value *R);
277 /// Compare two Instructions for equivalence, similar to
278 /// Instruction::isSameOperationAs but with modifications to the type
280 /// Stages are listed in "most significant stage first" order:
281 /// On each stage below, we do comparison between some left and right
282 /// operation parts. If parts are non-equal, we assign parts comparison
283 /// result to the operation comparison result and exit from method.
284 /// Otherwise we proceed to the next stage.
286 /// 1. Operations opcodes. Compared as numbers.
287 /// 2. Number of operands.
288 /// 3. Operation types. Compared with cmpType method.
289 /// 4. Compare operation subclass optional data as stream of bytes:
290 /// just convert it to integers and call cmpNumbers.
291 /// 5. Compare in operation operand types with cmpType in
292 /// most significant operand first order.
293 /// 6. Last stage. Check operations for some specific attributes.
294 /// For example, for Load it would be:
295 /// 6.1.Load: volatile (as boolean flag)
296 /// 6.2.Load: alignment (as integer numbers)
297 /// 6.3.Load: synch-scope (as integer numbers)
298 /// 6.4.Load: range metadata (as integer numbers)
299 /// On this stage its better to see the code, since its not more than 10-15
300 /// strings for particular instruction, and could change sometimes.
301 int cmpOperations(const Instruction *L, const Instruction *R) const;
303 /// Compare two GEPs for equivalent pointer arithmetic.
304 /// Parts to be compared for each comparison stage,
305 /// most significant stage first:
306 /// 1. Address space. As numbers.
307 /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
308 /// 3. Pointer operand type (using cmpType method).
309 /// 4. Number of operands.
310 /// 5. Compare operands, using cmpValues method.
311 int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR);
312 int cmpGEPs(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
313 return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
316 /// cmpType - compares two types,
317 /// defines total ordering among the types set.
320 /// 0 if types are equal,
321 /// -1 if Left is less than Right,
322 /// +1 if Left is greater than Right.
325 /// Comparison is broken onto stages. Like in lexicographical comparison
326 /// stage coming first has higher priority.
327 /// On each explanation stage keep in mind total ordering properties.
329 /// 0. Before comparison we coerce pointer types of 0 address space to
331 /// We also don't bother with same type at left and right, so
332 /// just return 0 in this case.
334 /// 1. If types are of different kind (different type IDs).
335 /// Return result of type IDs comparison, treating them as numbers.
336 /// 2. If types are vectors or integers, compare Type* values as numbers.
337 /// 3. Types has same ID, so check whether they belongs to the next group:
346 /// If so - return 0, yes - we can treat these types as equal only because
347 /// their IDs are same.
348 /// 4. If Left and Right are pointers, return result of address space
349 /// comparison (numbers comparison). We can treat pointer types of same
350 /// address space as equal.
351 /// 5. If types are complex.
352 /// Then both Left and Right are to be expanded and their element types will
353 /// be checked with the same way. If we get Res != 0 on some stage, return it.
354 /// Otherwise return 0.
355 /// 6. For all other cases put llvm_unreachable.
356 int cmpTypes(Type *TyL, Type *TyR) const;
358 int cmpNumbers(uint64_t L, uint64_t R) const;
360 int cmpAPInts(const APInt &L, const APInt &R) const;
361 int cmpAPFloats(const APFloat &L, const APFloat &R) const;
362 int cmpStrings(StringRef L, StringRef R) const;
363 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
365 // The two functions undergoing comparison.
366 const Function *FnL, *FnR;
368 /// Assign serial numbers to values from left function, and values from
371 /// Being comparing functions we need to compare values we meet at left and
373 /// Its easy to sort things out for external values. It just should be
374 /// the same value at left and right.
375 /// But for local values (those were introduced inside function body)
376 /// we have to ensure they were introduced at exactly the same place,
377 /// and plays the same role.
378 /// Let's assign serial number to each value when we meet it first time.
379 /// Values that were met at same place will be with same serial numbers.
380 /// In this case it would be good to explain few points about values assigned
381 /// to BBs and other ways of implementation (see below).
383 /// 1. Safety of BB reordering.
384 /// It's safe to change the order of BasicBlocks in function.
385 /// Relationship with other functions and serial numbering will not be
386 /// changed in this case.
387 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
388 /// from the entry, and then take each terminator. So it doesn't matter how in
389 /// fact BBs are ordered in function. And since cmpValues are called during
390 /// this walk, the numbering depends only on how BBs located inside the CFG.
391 /// So the answer is - yes. We will get the same numbering.
393 /// 2. Impossibility to use dominance properties of values.
394 /// If we compare two instruction operands: first is usage of local
395 /// variable AL from function FL, and second is usage of local variable AR
396 /// from FR, we could compare their origins and check whether they are
397 /// defined at the same place.
398 /// But, we are still not able to compare operands of PHI nodes, since those
399 /// could be operands from further BBs we didn't scan yet.
400 /// So it's impossible to use dominance properties in general.
401 DenseMap<const Value*, int> sn_mapL, sn_mapR;
405 mutable AssertingVH<Function> F;
406 FunctionComparator::FunctionHash Hash;
409 // Note the hash is recalculated potentially multiple times, but it is cheap.
410 FunctionNode(Function *F) : F(F), Hash(FunctionComparator::functionHash(*F)){}
411 Function *getFunc() const { return F; }
413 /// Replace the reference to the function F by the function G, assuming their
414 /// implementations are equal.
415 void replaceBy(Function *G) const {
416 assert(!(*this < FunctionNode(G)) && !(FunctionNode(G) < *this) &&
417 "The two functions must be equal");
422 void release() { F = 0; }
423 bool operator<(const FunctionNode &RHS) const {
424 // Order first by hashes, then full function comparison.
425 if (Hash != RHS.Hash)
426 return Hash < RHS.Hash;
427 return (FunctionComparator(F, RHS.getFunc()).compare()) == -1;
432 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
433 if (L < R) return -1;
438 int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
439 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
441 if (L.ugt(R)) return 1;
442 if (R.ugt(L)) return -1;
446 int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
447 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
448 (uint64_t)&R.getSemantics()))
450 return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
453 int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
454 // Prevent heavy comparison, compare sizes first.
455 if (int Res = cmpNumbers(L.size(), R.size()))
458 // Compare strings lexicographically only when it is necessary: only when
459 // strings are equal in size.
463 int FunctionComparator::cmpAttrs(const AttributeSet L,
464 const AttributeSet R) const {
465 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
468 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
469 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
471 for (; LI != LE && RI != RE; ++LI, ++RI) {
487 /// Constants comparison:
488 /// 1. Check whether type of L constant could be losslessly bitcasted to R
490 /// 2. Compare constant contents.
491 /// For more details see declaration comments.
492 int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
494 Type *TyL = L->getType();
495 Type *TyR = R->getType();
497 // Check whether types are bitcastable. This part is just re-factored
498 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
499 // we also pack into result which type is "less" for us.
500 int TypesRes = cmpTypes(TyL, TyR);
502 // Types are different, but check whether we can bitcast them.
503 if (!TyL->isFirstClassType()) {
504 if (TyR->isFirstClassType())
506 // Neither TyL nor TyR are values of first class type. Return the result
507 // of comparing the types
510 if (!TyR->isFirstClassType()) {
511 if (TyL->isFirstClassType())
516 // Vector -> Vector conversions are always lossless if the two vector types
517 // have the same size, otherwise not.
518 unsigned TyLWidth = 0;
519 unsigned TyRWidth = 0;
521 if (auto *VecTyL = dyn_cast<VectorType>(TyL))
522 TyLWidth = VecTyL->getBitWidth();
523 if (auto *VecTyR = dyn_cast<VectorType>(TyR))
524 TyRWidth = VecTyR->getBitWidth();
526 if (TyLWidth != TyRWidth)
527 return cmpNumbers(TyLWidth, TyRWidth);
529 // Zero bit-width means neither TyL nor TyR are vectors.
531 PointerType *PTyL = dyn_cast<PointerType>(TyL);
532 PointerType *PTyR = dyn_cast<PointerType>(TyR);
534 unsigned AddrSpaceL = PTyL->getAddressSpace();
535 unsigned AddrSpaceR = PTyR->getAddressSpace();
536 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
544 // TyL and TyR aren't vectors, nor pointers. We don't know how to
550 // OK, types are bitcastable, now check constant contents.
552 if (L->isNullValue() && R->isNullValue())
554 if (L->isNullValue() && !R->isNullValue())
556 if (!L->isNullValue() && R->isNullValue())
559 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
562 switch (L->getValueID()) {
563 case Value::UndefValueVal: return TypesRes;
564 case Value::ConstantIntVal: {
565 const APInt &LInt = cast<ConstantInt>(L)->getValue();
566 const APInt &RInt = cast<ConstantInt>(R)->getValue();
567 return cmpAPInts(LInt, RInt);
569 case Value::ConstantFPVal: {
570 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
571 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
572 return cmpAPFloats(LAPF, RAPF);
574 case Value::ConstantArrayVal: {
575 const ConstantArray *LA = cast<ConstantArray>(L);
576 const ConstantArray *RA = cast<ConstantArray>(R);
577 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
578 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
579 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
581 for (uint64_t i = 0; i < NumElementsL; ++i) {
582 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
583 cast<Constant>(RA->getOperand(i))))
588 case Value::ConstantStructVal: {
589 const ConstantStruct *LS = cast<ConstantStruct>(L);
590 const ConstantStruct *RS = cast<ConstantStruct>(R);
591 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
592 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
593 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
595 for (unsigned i = 0; i != NumElementsL; ++i) {
596 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
597 cast<Constant>(RS->getOperand(i))))
602 case Value::ConstantVectorVal: {
603 const ConstantVector *LV = cast<ConstantVector>(L);
604 const ConstantVector *RV = cast<ConstantVector>(R);
605 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
606 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
607 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
609 for (uint64_t i = 0; i < NumElementsL; ++i) {
610 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
611 cast<Constant>(RV->getOperand(i))))
616 case Value::ConstantExprVal: {
617 const ConstantExpr *LE = cast<ConstantExpr>(L);
618 const ConstantExpr *RE = cast<ConstantExpr>(R);
619 unsigned NumOperandsL = LE->getNumOperands();
620 unsigned NumOperandsR = RE->getNumOperands();
621 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
623 for (unsigned i = 0; i < NumOperandsL; ++i) {
624 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
625 cast<Constant>(RE->getOperand(i))))
630 case Value::FunctionVal:
631 case Value::GlobalVariableVal:
632 case Value::GlobalAliasVal:
633 default: // Unknown constant, cast L and R pointers to numbers and compare.
634 return cmpNumbers((uint64_t)L, (uint64_t)R);
638 /// cmpType - compares two types,
639 /// defines total ordering among the types set.
640 /// See method declaration comments for more details.
641 int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
643 PointerType *PTyL = dyn_cast<PointerType>(TyL);
644 PointerType *PTyR = dyn_cast<PointerType>(TyR);
646 const DataLayout &DL = FnL->getParent()->getDataLayout();
647 if (PTyL && PTyL->getAddressSpace() == 0)
648 TyL = DL.getIntPtrType(TyL);
649 if (PTyR && PTyR->getAddressSpace() == 0)
650 TyR = DL.getIntPtrType(TyR);
655 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
658 switch (TyL->getTypeID()) {
660 llvm_unreachable("Unknown type!");
661 // Fall through in Release mode.
662 case Type::IntegerTyID:
663 case Type::VectorTyID:
664 // TyL == TyR would have returned true earlier.
665 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
668 case Type::FloatTyID:
669 case Type::DoubleTyID:
670 case Type::X86_FP80TyID:
671 case Type::FP128TyID:
672 case Type::PPC_FP128TyID:
673 case Type::LabelTyID:
674 case Type::MetadataTyID:
675 case Type::TokenTyID:
678 case Type::PointerTyID: {
679 assert(PTyL && PTyR && "Both types must be pointers here.");
680 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
683 case Type::StructTyID: {
684 StructType *STyL = cast<StructType>(TyL);
685 StructType *STyR = cast<StructType>(TyR);
686 if (STyL->getNumElements() != STyR->getNumElements())
687 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
689 if (STyL->isPacked() != STyR->isPacked())
690 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
692 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
693 if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
699 case Type::FunctionTyID: {
700 FunctionType *FTyL = cast<FunctionType>(TyL);
701 FunctionType *FTyR = cast<FunctionType>(TyR);
702 if (FTyL->getNumParams() != FTyR->getNumParams())
703 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
705 if (FTyL->isVarArg() != FTyR->isVarArg())
706 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
708 if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
711 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
712 if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
718 case Type::ArrayTyID: {
719 ArrayType *ATyL = cast<ArrayType>(TyL);
720 ArrayType *ATyR = cast<ArrayType>(TyR);
721 if (ATyL->getNumElements() != ATyR->getNumElements())
722 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
723 return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
728 // Determine whether the two operations are the same except that pointer-to-A
729 // and pointer-to-B are equivalent. This should be kept in sync with
730 // Instruction::isSameOperationAs.
731 // Read method declaration comments for more details.
732 int FunctionComparator::cmpOperations(const Instruction *L,
733 const Instruction *R) const {
734 // Differences from Instruction::isSameOperationAs:
735 // * replace type comparison with calls to isEquivalentType.
736 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
737 // * because of the above, we don't test for the tail bit on calls later on
738 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
741 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
744 if (int Res = cmpTypes(L->getType(), R->getType()))
747 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
748 R->getRawSubclassOptionalData()))
751 if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
752 if (int Res = cmpTypes(AI->getAllocatedType(),
753 cast<AllocaInst>(R)->getAllocatedType()))
756 cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment()))
760 // We have two instructions of identical opcode and #operands. Check to see
761 // if all operands are the same type
762 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
764 cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
768 // Check special state that is a part of some instructions.
769 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
770 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
773 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
776 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
779 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
781 return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
782 (uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
784 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
786 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
789 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
792 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
794 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
796 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
797 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
798 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
799 if (int Res = cmpNumbers(CI->getCallingConv(),
800 cast<CallInst>(R)->getCallingConv()))
803 cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
806 (uint64_t)CI->getMetadata(LLVMContext::MD_range),
807 (uint64_t)cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
809 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
810 if (int Res = cmpNumbers(CI->getCallingConv(),
811 cast<InvokeInst>(R)->getCallingConv()))
814 cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
817 (uint64_t)CI->getMetadata(LLVMContext::MD_range),
818 (uint64_t)cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
820 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
821 ArrayRef<unsigned> LIndices = IVI->getIndices();
822 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
823 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
825 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
826 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
830 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
831 ArrayRef<unsigned> LIndices = EVI->getIndices();
832 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
833 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
835 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
836 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
840 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
842 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
844 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
847 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
848 if (int Res = cmpNumbers(CXI->isVolatile(),
849 cast<AtomicCmpXchgInst>(R)->isVolatile()))
851 if (int Res = cmpNumbers(CXI->isWeak(),
852 cast<AtomicCmpXchgInst>(R)->isWeak()))
854 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
855 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
857 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
858 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
860 return cmpNumbers(CXI->getSynchScope(),
861 cast<AtomicCmpXchgInst>(R)->getSynchScope());
863 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
864 if (int Res = cmpNumbers(RMWI->getOperation(),
865 cast<AtomicRMWInst>(R)->getOperation()))
867 if (int Res = cmpNumbers(RMWI->isVolatile(),
868 cast<AtomicRMWInst>(R)->isVolatile()))
870 if (int Res = cmpNumbers(RMWI->getOrdering(),
871 cast<AtomicRMWInst>(R)->getOrdering()))
873 return cmpNumbers(RMWI->getSynchScope(),
874 cast<AtomicRMWInst>(R)->getSynchScope());
879 // Determine whether two GEP operations perform the same underlying arithmetic.
880 // Read method declaration comments for more details.
881 int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
882 const GEPOperator *GEPR) {
884 unsigned int ASL = GEPL->getPointerAddressSpace();
885 unsigned int ASR = GEPR->getPointerAddressSpace();
887 if (int Res = cmpNumbers(ASL, ASR))
890 // When we have target data, we can reduce the GEP down to the value in bytes
891 // added to the address.
892 const DataLayout &DL = FnL->getParent()->getDataLayout();
893 unsigned BitWidth = DL.getPointerSizeInBits(ASL);
894 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
895 if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
896 GEPR->accumulateConstantOffset(DL, OffsetR))
897 return cmpAPInts(OffsetL, OffsetR);
899 if (int Res = cmpNumbers((uint64_t)GEPL->getPointerOperand()->getType(),
900 (uint64_t)GEPR->getPointerOperand()->getType()))
903 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
906 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
907 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
914 /// Compare two values used by the two functions under pair-wise comparison. If
915 /// this is the first time the values are seen, they're added to the mapping so
916 /// that we will detect mismatches on next use.
917 /// See comments in declaration for more details.
918 int FunctionComparator::cmpValues(const Value *L, const Value *R) {
919 // Catch self-reference case.
931 const Constant *ConstL = dyn_cast<Constant>(L);
932 const Constant *ConstR = dyn_cast<Constant>(R);
933 if (ConstL && ConstR) {
936 return cmpConstants(ConstL, ConstR);
944 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
945 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
947 if (InlineAsmL && InlineAsmR)
948 return cmpNumbers((uint64_t)L, (uint64_t)R);
954 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
955 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
957 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
959 // Test whether two basic blocks have equivalent behaviour.
960 int FunctionComparator::compare(const BasicBlock *BBL, const BasicBlock *BBR) {
961 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
962 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
965 if (int Res = cmpValues(InstL, InstR))
968 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
969 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
978 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
980 if (int Res = cmpGEPs(GEPL, GEPR))
983 if (int Res = cmpOperations(InstL, InstR))
985 assert(InstL->getNumOperands() == InstR->getNumOperands());
987 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
988 Value *OpL = InstL->getOperand(i);
989 Value *OpR = InstR->getOperand(i);
990 if (int Res = cmpValues(OpL, OpR))
992 if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
994 // TODO: Already checked in cmpOperation
995 if (int Res = cmpTypes(OpL->getType(), OpR->getType()))
1001 } while (InstL != InstLE && InstR != InstRE);
1003 if (InstL != InstLE && InstR == InstRE)
1005 if (InstL == InstLE && InstR != InstRE)
1010 // Test whether the two functions have equivalent behaviour.
1011 int FunctionComparator::compare() {
1016 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1019 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1023 if (int Res = cmpNumbers((uint64_t)FnL->getGC(), (uint64_t)FnR->getGC()))
1027 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1030 if (FnL->hasSection()) {
1031 if (int Res = cmpStrings(FnL->getSection(), FnR->getSection()))
1035 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1038 // TODO: if it's internal and only used in direct calls, we could handle this
1040 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1043 if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
1046 assert(FnL->arg_size() == FnR->arg_size() &&
1047 "Identically typed functions have different numbers of args!");
1049 // Visit the arguments so that they get enumerated in the order they're
1051 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1052 ArgRI = FnR->arg_begin(),
1053 ArgLE = FnL->arg_end();
1054 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1055 if (cmpValues(ArgLI, ArgRI) != 0)
1056 llvm_unreachable("Arguments repeat!");
1059 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1060 // linked list is immaterial. Our walk starts at the entry block for both
1061 // functions, then takes each block from each terminator in order. As an
1062 // artifact, this also means that unreachable blocks are ignored.
1063 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
1064 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
1066 FnLBBs.push_back(&FnL->getEntryBlock());
1067 FnRBBs.push_back(&FnR->getEntryBlock());
1069 VisitedBBs.insert(FnLBBs[0]);
1070 while (!FnLBBs.empty()) {
1071 const BasicBlock *BBL = FnLBBs.pop_back_val();
1072 const BasicBlock *BBR = FnRBBs.pop_back_val();
1074 if (int Res = cmpValues(BBL, BBR))
1077 if (int Res = compare(BBL, BBR))
1080 const TerminatorInst *TermL = BBL->getTerminator();
1081 const TerminatorInst *TermR = BBR->getTerminator();
1083 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1084 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
1085 if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
1088 FnLBBs.push_back(TermL->getSuccessor(i));
1089 FnRBBs.push_back(TermR->getSuccessor(i));
1095 // Accumulate the hash of a sequence of 64-bit integers. This is similar to a
1096 // hash of a sequence of 64bit ints, but the entire input does not need to be
1097 // available at once. This interface is necessary for functionHash because it
1098 // needs to accumulate the hash as the structure of the function is traversed
1099 // without saving these values to an intermediate buffer. This form of hashing
1100 // is not often needed, as usually the object to hash is just read from a
1102 class HashAccumulator64 {
1105 // Initialize to random constant, so the state isn't zero.
1106 HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
1107 void add(uint64_t V) {
1108 Hash = llvm::hashing::detail::hash_16_bytes(Hash, V);
1110 // No finishing is required, because the entire hash value is used.
1111 uint64_t getHash() { return Hash; }
1114 // A function hash is calculated by considering only the number of arguments and
1115 // whether a function is varargs, the order of basic blocks (given by the
1116 // successors of each basic block in depth first order), and the order of
1117 // opcodes of each instruction within each of these basic blocks. This mirrors
1118 // the strategy compare() uses to compare functions by walking the BBs in depth
1119 // first order and comparing each instruction in sequence. Because this hash
1120 // does not look at the operands, it is insensitive to things such as the
1121 // target of calls and the constants used in the function, which makes it useful
1122 // when possibly merging functions which are the same modulo constants and call
1124 FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
1125 HashAccumulator64 H;
1126 H.add(F.isVarArg());
1127 H.add(F.arg_size());
1129 SmallVector<const BasicBlock *, 8> BBs;
1130 SmallSet<const BasicBlock *, 16> VisitedBBs;
1132 // Walk the blocks in the same order as FunctionComparator::compare(),
1133 // accumulating the hash of the function "structure." (BB and opcode sequence)
1134 BBs.push_back(&F.getEntryBlock());
1135 VisitedBBs.insert(BBs[0]);
1136 while (!BBs.empty()) {
1137 const BasicBlock *BB = BBs.pop_back_val();
1138 // This random value acts as a block header, as otherwise the partition of
1139 // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
1141 for (auto &Inst : *BB) {
1142 H.add(Inst.getOpcode());
1144 const TerminatorInst *Term = BB->getTerminator();
1145 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
1146 if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
1148 BBs.push_back(Term->getSuccessor(i));
1157 /// MergeFunctions finds functions which will generate identical machine code,
1158 /// by considering all pointer types to be equivalent. Once identified,
1159 /// MergeFunctions will fold them by replacing a call to one to a call to a
1160 /// bitcast of the other.
1162 class MergeFunctions : public ModulePass {
1166 : ModulePass(ID), HasGlobalAliases(false) {
1167 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1170 bool runOnModule(Module &M) override;
1173 typedef std::set<FunctionNode> FnTreeType;
1175 /// A work queue of functions that may have been modified and should be
1177 std::vector<WeakVH> Deferred;
1179 /// Checks the rules of order relation introduced among functions set.
1180 /// Returns true, if sanity check has been passed, and false if failed.
1181 bool doSanityCheck(std::vector<WeakVH> &Worklist);
1183 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
1184 /// equal to one that's already present.
1185 bool insert(Function *NewFunction);
1187 /// Remove a Function from the FnTree and queue it up for a second sweep of
1189 void remove(Function *F);
1191 /// Find the functions that use this Value and remove them from FnTree and
1192 /// queue the functions.
1193 void removeUsers(Value *V);
1195 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1196 /// necessary to make types match.
1197 void replaceDirectCallers(Function *Old, Function *New);
1199 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1200 /// be converted into a thunk. In either case, it should never be visited
1202 void mergeTwoFunctions(Function *F, Function *G);
1204 /// Replace G with a thunk or an alias to F. Deletes G.
1205 void writeThunkOrAlias(Function *F, Function *G);
1207 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1208 /// of G with bitcast(F). Deletes G.
1209 void writeThunk(Function *F, Function *G);
1211 /// Replace G with an alias to F. Deletes G.
1212 void writeAlias(Function *F, Function *G);
1214 /// Replace function F with function G in the function tree.
1215 void replaceFunctionInTree(FnTreeType::iterator &IterToF, Function *G);
1217 /// The set of all distinct functions. Use the insert() and remove() methods
1221 /// Whether or not the target supports global aliases.
1222 bool HasGlobalAliases;
1225 } // end anonymous namespace
1227 char MergeFunctions::ID = 0;
1228 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1230 ModulePass *llvm::createMergeFunctionsPass() {
1231 return new MergeFunctions();
1234 bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1235 if (const unsigned Max = NumFunctionsForSanityCheck) {
1236 unsigned TripleNumber = 0;
1239 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1242 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1243 I != E && i < Max; ++I, ++i) {
1245 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1246 Function *F1 = cast<Function>(*I);
1247 Function *F2 = cast<Function>(*J);
1248 int Res1 = FunctionComparator(F1, F2).compare();
1249 int Res2 = FunctionComparator(F2, F1).compare();
1251 // If F1 <= F2, then F2 >= F1, otherwise report failure.
1252 if (Res1 != -Res2) {
1253 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1264 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1265 ++k, ++K, ++TripleNumber) {
1269 Function *F3 = cast<Function>(*K);
1270 int Res3 = FunctionComparator(F1, F3).compare();
1271 int Res4 = FunctionComparator(F2, F3).compare();
1273 bool Transitive = true;
1275 if (Res1 != 0 && Res1 == Res4) {
1276 // F1 > F2, F2 > F3 => F1 > F3
1277 Transitive = Res3 == Res1;
1278 } else if (Res3 != 0 && Res3 == -Res4) {
1279 // F1 > F3, F3 > F2 => F1 > F2
1280 Transitive = Res3 == Res1;
1281 } else if (Res4 != 0 && -Res3 == Res4) {
1282 // F2 > F3, F3 > F1 => F2 > F1
1283 Transitive = Res4 == -Res1;
1287 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1288 << TripleNumber << "\n";
1289 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1300 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1306 bool MergeFunctions::runOnModule(Module &M) {
1307 bool Changed = false;
1309 // All functions in the module, ordered by hash. Functions with a unique
1310 // hash value are easily eliminated.
1311 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
1313 for (Function &Func : M) {
1314 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
1315 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
1319 std::sort(HashedFuncs.begin(), HashedFuncs.end());
1321 auto S = HashedFuncs.begin();
1322 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
1323 // If the hash value matches the previous value or the next one, we must
1324 // consider merging it. Otherwise it is dropped and never considered again.
1325 if ((I != S && std::prev(I)->first == I->first) ||
1326 (std::next(I) != IE && std::next(I)->first == I->first) ) {
1327 Deferred.push_back(WeakVH(I->second));
1332 std::vector<WeakVH> Worklist;
1333 Deferred.swap(Worklist);
1335 DEBUG(doSanityCheck(Worklist));
1337 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1338 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1340 // Insert only strong functions and merge them. Strong function merging
1341 // always deletes one of them.
1342 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1343 E = Worklist.end(); I != E; ++I) {
1345 Function *F = cast<Function>(*I);
1346 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1347 !F->mayBeOverridden()) {
1348 Changed |= insert(F);
1352 // Insert only weak functions and merge them. By doing these second we
1353 // create thunks to the strong function when possible. When two weak
1354 // functions are identical, we create a new strong function with two weak
1355 // weak thunks to it which are identical but not mergable.
1356 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1357 E = Worklist.end(); I != E; ++I) {
1359 Function *F = cast<Function>(*I);
1360 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1361 F->mayBeOverridden()) {
1362 Changed |= insert(F);
1365 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
1366 } while (!Deferred.empty());
1373 // Replace direct callers of Old with New.
1374 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1375 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
1376 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1379 CallSite CS(U->getUser());
1380 if (CS && CS.isCallee(U)) {
1381 // Transfer the called function's attributes to the call site. Due to the
1382 // bitcast we will 'loose' ABI changing attributes because the 'called
1383 // function' is no longer a Function* but the bitcast. Code that looks up
1384 // the attributes from the called function will fail.
1385 auto &Context = New->getContext();
1386 auto NewFuncAttrs = New->getAttributes();
1387 auto CallSiteAttrs = CS.getAttributes();
1389 CallSiteAttrs = CallSiteAttrs.addAttributes(
1390 Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes());
1392 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) {
1393 AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx);
1394 if (Attrs.getNumSlots())
1395 CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs);
1398 CS.setAttributes(CallSiteAttrs);
1400 remove(CS.getInstruction()->getParent()->getParent());
1406 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1407 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
1408 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1409 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1410 G->hasWeakLinkage()) {
1419 // Helper for writeThunk,
1420 // Selects proper bitcast operation,
1421 // but a bit simpler then CastInst::getCastOpcode.
1422 static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
1423 Type *SrcTy = V->getType();
1424 if (SrcTy->isStructTy()) {
1425 assert(DestTy->isStructTy());
1426 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1427 Value *Result = UndefValue::get(DestTy);
1428 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1429 Value *Element = createCast(
1430 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
1431 DestTy->getStructElementType(I));
1434 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
1438 assert(!DestTy->isStructTy());
1439 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1440 return Builder.CreateIntToPtr(V, DestTy);
1441 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1442 return Builder.CreatePtrToInt(V, DestTy);
1444 return Builder.CreateBitCast(V, DestTy);
1447 // Replace G with a simple tail call to bitcast(F). Also replace direct uses
1448 // of G with bitcast(F). Deletes G.
1449 void MergeFunctions::writeThunk(Function *F, Function *G) {
1450 if (!G->mayBeOverridden()) {
1451 // Redirect direct callers of G to F.
1452 replaceDirectCallers(G, F);
1455 // If G was internal then we may have replaced all uses of G with F. If so,
1456 // stop here and delete G. There's no need for a thunk.
1457 if (G->hasLocalLinkage() && G->use_empty()) {
1458 G->eraseFromParent();
1462 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1464 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
1465 IRBuilder<false> Builder(BB);
1467 SmallVector<Value *, 16> Args;
1469 FunctionType *FFTy = F->getFunctionType();
1470 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1472 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
1476 CallInst *CI = Builder.CreateCall(F, Args);
1478 CI->setCallingConv(F->getCallingConv());
1479 if (NewG->getReturnType()->isVoidTy()) {
1480 Builder.CreateRetVoid();
1482 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
1485 NewG->copyAttributesFrom(G);
1488 G->replaceAllUsesWith(NewG);
1489 G->eraseFromParent();
1491 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
1495 // Replace G with an alias to F and delete G.
1496 void MergeFunctions::writeAlias(Function *F, Function *G) {
1497 PointerType *PTy = G->getType();
1498 auto *GA = GlobalAlias::create(PTy, G->getLinkage(), "", F);
1499 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1501 GA->setVisibility(G->getVisibility());
1503 G->replaceAllUsesWith(GA);
1504 G->eraseFromParent();
1506 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
1507 ++NumAliasesWritten;
1510 // Merge two equivalent functions. Upon completion, Function G is deleted.
1511 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
1512 if (F->mayBeOverridden()) {
1513 assert(G->mayBeOverridden());
1515 // Make them both thunks to the same internal function.
1516 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1518 H->copyAttributesFrom(F);
1521 F->replaceAllUsesWith(H);
1523 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1525 if (HasGlobalAliases) {
1533 F->setAlignment(MaxAlignment);
1534 F->setLinkage(GlobalValue::PrivateLinkage);
1537 writeThunkOrAlias(F, G);
1540 ++NumFunctionsMerged;
1543 /// Replace function F for function G in the map.
1544 void MergeFunctions::replaceFunctionInTree(FnTreeType::iterator &IterToF,
1546 Function *F = IterToF->getFunc();
1548 // A total order is already guaranteed otherwise because we process strong
1549 // functions before weak functions.
1550 assert(((F->mayBeOverridden() && G->mayBeOverridden()) ||
1551 (!F->mayBeOverridden() && !G->mayBeOverridden())) &&
1552 "Only change functions if both are strong or both are weak");
1555 IterToF->replaceBy(G);
1558 // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
1559 // that was already inserted.
1560 bool MergeFunctions::insert(Function *NewFunction) {
1561 std::pair<FnTreeType::iterator, bool> Result =
1562 FnTree.insert(FunctionNode(NewFunction));
1564 if (Result.second) {
1565 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
1569 const FunctionNode &OldF = *Result.first;
1571 // Don't merge tiny functions, since it can just end up making the function
1573 // FIXME: Should still merge them if they are unnamed_addr and produce an
1575 if (NewFunction->size() == 1) {
1576 if (NewFunction->front().size() <= 2) {
1577 DEBUG(dbgs() << NewFunction->getName()
1578 << " is to small to bother merging\n");
1583 // Impose a total order (by name) on the replacement of functions. This is
1584 // important when operating on more than one module independently to prevent
1585 // cycles of thunks calling each other when the modules are linked together.
1587 // When one function is weak and the other is strong there is an order imposed
1588 // already. We process strong functions before weak functions.
1589 if ((OldF.getFunc()->mayBeOverridden() && NewFunction->mayBeOverridden()) ||
1590 (!OldF.getFunc()->mayBeOverridden() && !NewFunction->mayBeOverridden()))
1591 if (OldF.getFunc()->getName() > NewFunction->getName()) {
1592 // Swap the two functions.
1593 Function *F = OldF.getFunc();
1594 replaceFunctionInTree(Result.first, NewFunction);
1596 assert(OldF.getFunc() != F && "Must have swapped the functions.");
1599 // Never thunk a strong function to a weak function.
1600 assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
1602 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
1603 << " == " << NewFunction->getName() << '\n');
1605 Function *DeleteF = NewFunction;
1606 mergeTwoFunctions(OldF.getFunc(), DeleteF);
1610 // Remove a function from FnTree. If it was already in FnTree, add
1611 // it to Deferred so that we'll look at it in the next round.
1612 void MergeFunctions::remove(Function *F) {
1613 // We need to make sure we remove F, not a function "equal" to F per the
1614 // function equality comparator.
1615 FnTreeType::iterator found = FnTree.find(FunctionNode(F));
1617 if (found != FnTree.end() && found->getFunc() == F) {
1619 FnTree.erase(found);
1623 DEBUG(dbgs() << "Removed " << F->getName()
1624 << " from set and deferred it.\n");
1625 Deferred.emplace_back(F);
1629 // For each instruction used by the value, remove() the function that contains
1630 // the instruction. This should happen right before a call to RAUW.
1631 void MergeFunctions::removeUsers(Value *V) {
1632 std::vector<Value *> Worklist;
1633 Worklist.push_back(V);
1634 SmallSet<Value*, 8> Visited;
1636 while (!Worklist.empty()) {
1637 Value *V = Worklist.back();
1638 Worklist.pop_back();
1640 for (User *U : V->users()) {
1641 if (Instruction *I = dyn_cast<Instruction>(U)) {
1642 remove(I->getParent()->getParent());
1643 } else if (isa<GlobalValue>(U)) {
1645 } else if (Constant *C = dyn_cast<Constant>(U)) {
1646 for (User *UU : C->users()) {
1647 if (!Visited.insert(UU).second)
1648 Worklist.push_back(UU);