blob: 49dcb39780a0148ba109934cfea4f8ba60f9641a [file] [log] [blame]
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001//===- 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//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000012// A hash is computed from the function, based on its type and number of
13// basic blocks.
14//
15// Once all hashes are computed, we perform an expensive equality comparison
16// on each function pair. This takes n^2/2 comparisons per bucket, so it's
17// important that the hash function be high quality. The equality comparison
18// iterates through each instruction in each basic block.
19//
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000020// When a match is found the functions are folded. If both functions are
21// overridable, we move the functionality into a new internal function and
22// leave two overridable thunks to it.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000023//
24//===----------------------------------------------------------------------===//
25//
26// Future work:
27//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000028// * virtual functions.
29//
30// Many functions have their address taken by the virtual function table for
31// the object they belong to. However, as long as it's only used for a lookup
Nick Lewyckyfbd27572010-08-08 05:04:23 +000032// and call, this is irrelevant, and we'd like to fold such functions.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000033//
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +000034// * switch from n^2 pair-wise comparisons to an n-way comparison for each
35// bucket.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000036//
Nick Lewyckyfbd27572010-08-08 05:04:23 +000037// * be smarter about bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000038//
39// In order to fold functions, we will sometimes add either bitcast instructions
40// or bitcast constant expressions. Unfortunately, this can confound further
41// analysis since the two functions differ where one has a bitcast and the
Nick Lewyckyfbd27572010-08-08 05:04:23 +000042// other doesn't. We should learn to look through bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000043//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000044//===----------------------------------------------------------------------===//
45
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000046#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000047#include "llvm/ADT/DenseSet.h"
48#include "llvm/ADT/FoldingSet.h"
49#include "llvm/ADT/STLExtras.h"
50#include "llvm/ADT/SmallSet.h"
51#include "llvm/ADT/Statistic.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000052#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InlineAsm.h"
57#include "llvm/IR/Instructions.h"
58#include "llvm/IR/LLVMContext.h"
59#include "llvm/IR/Module.h"
60#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000061#include "llvm/IR/ValueHandle.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000062#include "llvm/Pass.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000063#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000064#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000065#include "llvm/Support/raw_ostream.h"
Nick Lewycky68984ed2010-08-31 08:29:37 +000066#include <vector>
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000067using namespace llvm;
68
Chandler Carruth964daaa2014-04-22 02:55:47 +000069#define DEBUG_TYPE "mergefunc"
70
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000071STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +000072STATISTIC(NumThunksWritten, "Number of thunks generated");
Nick Lewyckyf1cec162011-01-25 08:56:50 +000073STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky71972d42010-09-07 01:42:10 +000074STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000075
Benjamin Kramer630e6e12013-04-19 23:06:44 +000076/// Returns the type id for a type to be hashed. We turn pointer types into
77/// integers here because the actual compare logic below considers pointers and
78/// integers of the same size as equal.
79static Type::TypeID getTypeIDForHash(Type *Ty) {
80 if (Ty->isPointerTy())
81 return Type::IntegerTyID;
82 return Ty->getTypeID();
83}
84
Nick Lewyckycfb284c2011-01-28 08:43:14 +000085/// Creates a hash-code for the function which is the same for any two
86/// functions that will compare equal, without looking at the instructions
87/// inside the function.
88static unsigned profileFunction(const Function *F) {
Chris Lattner229907c2011-07-18 04:54:35 +000089 FunctionType *FTy = F->getFunctionType();
Nick Lewyckyfbd27572010-08-08 05:04:23 +000090
Nick Lewycky00959372010-09-05 08:22:49 +000091 FoldingSetNodeID ID;
92 ID.AddInteger(F->size());
93 ID.AddInteger(F->getCallingConv());
94 ID.AddBoolean(F->hasGC());
95 ID.AddBoolean(FTy->isVarArg());
Benjamin Kramer630e6e12013-04-19 23:06:44 +000096 ID.AddInteger(getTypeIDForHash(FTy->getReturnType()));
Nick Lewycky00959372010-09-05 08:22:49 +000097 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Benjamin Kramer630e6e12013-04-19 23:06:44 +000098 ID.AddInteger(getTypeIDForHash(FTy->getParamType(i)));
Nick Lewycky00959372010-09-05 08:22:49 +000099 return ID.ComputeHash();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000100}
101
Nick Lewycky71972d42010-09-07 01:42:10 +0000102namespace {
103
Nick Lewyckyaaf40122011-01-28 08:19:00 +0000104/// ComparableFunction - A struct that pairs together functions with a
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000105/// DataLayout so that we can keep them together as elements in the DenseSet.
Nick Lewycky00959372010-09-05 08:22:49 +0000106class ComparableFunction {
107public:
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000108 static const ComparableFunction EmptyKey;
109 static const ComparableFunction TombstoneKey;
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000110 static DataLayout * const LookupOnly;
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000111
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000112 ComparableFunction(Function *Func, const DataLayout *DL)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000113 : Func(Func), Hash(profileFunction(Func)), DL(DL) {}
Nick Lewycky00959372010-09-05 08:22:49 +0000114
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000115 Function *getFunc() const { return Func; }
116 unsigned getHash() const { return Hash; }
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000117 const DataLayout *getDataLayout() const { return DL; }
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000118
119 // Drops AssertingVH reference to the function. Outside of debug mode, this
120 // does nothing.
121 void release() {
122 assert(Func &&
123 "Attempted to release function twice, or release empty/tombstone!");
Craig Topperf40110f2014-04-25 05:29:35 +0000124 Func = nullptr;
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000125 }
126
127private:
128 explicit ComparableFunction(unsigned Hash)
Craig Topperf40110f2014-04-25 05:29:35 +0000129 : Func(nullptr), Hash(Hash), DL(nullptr) {}
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000130
131 AssertingVH<Function> Func;
132 unsigned Hash;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000133 const DataLayout *DL;
Nick Lewycky00959372010-09-05 08:22:49 +0000134};
135
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000136const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
137const ComparableFunction ComparableFunction::TombstoneKey =
138 ComparableFunction(1);
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000139DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1);
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000140
Nick Lewycky71972d42010-09-07 01:42:10 +0000141}
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000142
143namespace llvm {
144 template <>
145 struct DenseMapInfo<ComparableFunction> {
146 static ComparableFunction getEmptyKey() {
147 return ComparableFunction::EmptyKey;
148 }
149 static ComparableFunction getTombstoneKey() {
150 return ComparableFunction::TombstoneKey;
151 }
152 static unsigned getHashValue(const ComparableFunction &CF) {
153 return CF.getHash();
154 }
155 static bool isEqual(const ComparableFunction &LHS,
156 const ComparableFunction &RHS);
157 };
158}
159
160namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000161
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000162/// FunctionComparator - Compares two functions to determine whether or not
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000163/// they will generate machine code with the same behaviour. DataLayout is
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000164/// used if available. The comparator always fails conservatively (erring on the
165/// side of claiming that two functions are different).
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000166class FunctionComparator {
167public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000168 FunctionComparator(const DataLayout *DL, const Function *F1,
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000169 const Function *F2)
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000170 : FnL(F1), FnR(F2), DL(DL) {}
Nick Lewyckye04dc222009-06-12 08:04:51 +0000171
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000172 /// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000173 int compare();
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000174
175private:
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000176 /// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000177 int compare(const BasicBlock *BBL, const BasicBlock *BBR);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000178
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000179 /// Constants comparison.
180 /// Its analog to lexicographical comparison between hypothetical numbers
181 /// of next format:
182 /// <bitcastability-trait><raw-bit-contents>
183 ///
184 /// 1. Bitcastability.
185 /// Check whether L's type could be losslessly bitcasted to R's type.
186 /// On this stage method, in case when lossless bitcast is not possible
187 /// method returns -1 or 1, thus also defining which type is greater in
188 /// context of bitcastability.
189 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
190 /// to the contents comparison.
191 /// If types differ, remember types comparison result and check
192 /// whether we still can bitcast types.
193 /// Stage 1: Types that satisfies isFirstClassType conditions are always
194 /// greater then others.
195 /// Stage 2: Vector is greater then non-vector.
196 /// If both types are vectors, then vector with greater bitwidth is
197 /// greater.
198 /// If both types are vectors with the same bitwidth, then types
199 /// are bitcastable, and we can skip other stages, and go to contents
200 /// comparison.
201 /// Stage 3: Pointer types are greater than non-pointers. If both types are
202 /// pointers of the same address space - go to contents comparison.
203 /// Different address spaces: pointer with greater address space is
204 /// greater.
205 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
206 /// We don't know how to bitcast them. So, we better don't do it,
207 /// and return types comparison result (so it determines the
208 /// relationship among constants we don't know how to bitcast).
209 ///
210 /// Just for clearance, let's see how the set of constants could look
211 /// on single dimension axis:
212 ///
213 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
214 /// Where: NFCT - Not a FirstClassType
215 /// FCT - FirstClassTyp:
216 ///
217 /// 2. Compare raw contents.
218 /// It ignores types on this stage and only compares bits from L and R.
219 /// Returns 0, if L and R has equivalent contents.
220 /// -1 or 1 if values are different.
221 /// Pretty trivial:
222 /// 2.1. If contents are numbers, compare numbers.
223 /// Ints with greater bitwidth are greater. Ints with same bitwidths
224 /// compared by their contents.
225 /// 2.2. "And so on". Just to avoid discrepancies with comments
226 /// perhaps it would be better to read the implementation itself.
227 /// 3. And again about overall picture. Let's look back at how the ordered set
228 /// of constants will look like:
229 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
230 ///
231 /// Now look, what could be inside [FCT, "others"], for example:
232 /// [FCT, "others"] =
233 /// [
234 /// [double 0.1], [double 1.23],
235 /// [i32 1], [i32 2],
236 /// { double 1.0 }, ; StructTyID, NumElements = 1
237 /// { i32 1 }, ; StructTyID, NumElements = 1
238 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
239 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
240 /// ]
241 ///
242 /// Let's explain the order. Float numbers will be less than integers, just
243 /// because of cmpType terms: FloatTyID < IntegerTyID.
244 /// Floats (with same fltSemantics) are sorted according to their value.
245 /// Then you can see integers, and they are, like a floats,
246 /// could be easy sorted among each others.
247 /// The structures. Structures are grouped at the tail, again because of their
248 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
249 /// Structures with greater number of elements are greater. Structures with
250 /// greater elements going first are greater.
251 /// The same logic with vectors, arrays and other possible complex types.
252 ///
253 /// Bitcastable constants.
254 /// Let's assume, that some constant, belongs to some group of
255 /// "so-called-equal" values with different types, and at the same time
256 /// belongs to another group of constants with equal types
257 /// and "really" equal values.
258 ///
259 /// Now, prove that this is impossible:
260 ///
261 /// If constant A with type TyA is bitcastable to B with type TyB, then:
262 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
263 /// those should be vectors (if TyA is vector), pointers
264 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
265 /// be equal to TyB.
266 /// 2. All constants with non-equal, but bitcastable types to TyA, are
267 /// bitcastable to B.
268 /// Once again, just because we allow it to vectors and pointers only.
269 /// This statement could be expanded as below:
270 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
271 /// vector B, and thus bitcastable to B as well.
272 /// 2.2. All pointers of the same address space, no matter what they point to,
273 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
274 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
275 /// QED.
276 ///
277 /// In another words, for pointers and vectors, we ignore top-level type and
278 /// look at their particular properties (bit-width for vectors, and
279 /// address space for pointers).
280 /// If these properties are equal - compare their contents.
281 int cmpConstants(const Constant *L, const Constant *R);
282
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000283 /// Assign or look up previously assigned numbers for the two values, and
284 /// return whether the numbers are equal. Numbers are assigned in the order
285 /// visited.
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000286 /// Comparison order:
287 /// Stage 0: Value that is function itself is always greater then others.
288 /// If left and right values are references to their functions, then
289 /// they are equal.
290 /// Stage 1: Constants are greater than non-constants.
291 /// If both left and right are constants, then the result of
292 /// cmpConstants is used as cmpValues result.
293 /// Stage 2: InlineAsm instances are greater than others. If both left and
294 /// right are InlineAsm instances, InlineAsm* pointers casted to
295 /// integers and compared as numbers.
296 /// Stage 3: For all other cases we compare order we meet these values in
297 /// their functions. If right value was met first during scanning,
298 /// then left value is greater.
299 /// In another words, we compare serial numbers, for more details
300 /// see comments for sn_mapL and sn_mapR.
301 int cmpValues(const Value *L, const Value *R);
302
303 bool enumerate(const Value *V1, const Value *V2) {
304 return cmpValues(V1, V2) == 0;
305 }
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000306
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000307 /// Compare two Instructions for equivalence, similar to
308 /// Instruction::isSameOperationAs but with modifications to the type
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000309 /// comparison.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000310 /// Stages are listed in "most significant stage first" order:
311 /// On each stage below, we do comparison between some left and right
312 /// operation parts. If parts are non-equal, we assign parts comparison
313 /// result to the operation comparison result and exit from method.
314 /// Otherwise we proceed to the next stage.
315 /// Stages:
316 /// 1. Operations opcodes. Compared as numbers.
317 /// 2. Number of operands.
318 /// 3. Operation types. Compared with cmpType method.
319 /// 4. Compare operation subclass optional data as stream of bytes:
320 /// just convert it to integers and call cmpNumbers.
321 /// 5. Compare in operation operand types with cmpType in
322 /// most significant operand first order.
323 /// 6. Last stage. Check operations for some specific attributes.
324 /// For example, for Load it would be:
325 /// 6.1.Load: volatile (as boolean flag)
326 /// 6.2.Load: alignment (as integer numbers)
327 /// 6.3.Load: synch-scope (as integer numbers)
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000328 /// 6.4.Load: range metadata (as integer numbers)
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000329 /// On this stage its better to see the code, since its not more than 10-15
330 /// strings for particular instruction, and could change sometimes.
331 int cmpOperation(const Instruction *L, const Instruction *R) const;
332
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000333 bool isEquivalentOperation(const Instruction *I1,
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000334 const Instruction *I2) const {
335 return cmpOperation(I1, I2) == 0;
336 }
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000337
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000338 /// Compare two GEPs for equivalent pointer arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000339 /// Parts to be compared for each comparison stage,
340 /// most significant stage first:
341 /// 1. Address space. As numbers.
342 /// 2. Constant offset, (if "DataLayout *DL" field is not NULL,
343 /// using GEPOperator::accumulateConstantOffset method).
344 /// 3. Pointer operand type (using cmpType method).
345 /// 4. Number of operands.
346 /// 5. Compare operands, using cmpValues method.
347 int cmpGEP(const GEPOperator *GEPL, const GEPOperator *GEPR);
348 int cmpGEP(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
349 return cmpGEP(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
350 }
351
352 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2) {
353 return cmpGEP(GEP1, GEP2) == 0;
354 }
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000355 bool isEquivalentGEP(const GetElementPtrInst *GEP1,
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000356 const GetElementPtrInst *GEP2) {
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000357 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
358 }
359
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000360 /// cmpType - compares two types,
361 /// defines total ordering among the types set.
362 ///
363 /// Return values:
364 /// 0 if types are equal,
365 /// -1 if Left is less than Right,
366 /// +1 if Left is greater than Right.
367 ///
368 /// Description:
369 /// Comparison is broken onto stages. Like in lexicographical comparison
370 /// stage coming first has higher priority.
371 /// On each explanation stage keep in mind total ordering properties.
372 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000373 /// 0. Before comparison we coerce pointer types of 0 address space to
374 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000375 /// We also don't bother with same type at left and right, so
376 /// just return 0 in this case.
377 ///
378 /// 1. If types are of different kind (different type IDs).
379 /// Return result of type IDs comparison, treating them as numbers.
380 /// 2. If types are vectors or integers, compare Type* values as numbers.
381 /// 3. Types has same ID, so check whether they belongs to the next group:
382 /// * Void
383 /// * Float
384 /// * Double
385 /// * X86_FP80
386 /// * FP128
387 /// * PPC_FP128
388 /// * Label
389 /// * Metadata
390 /// If so - return 0, yes - we can treat these types as equal only because
391 /// their IDs are same.
392 /// 4. If Left and Right are pointers, return result of address space
393 /// comparison (numbers comparison). We can treat pointer types of same
394 /// address space as equal.
395 /// 5. If types are complex.
396 /// Then both Left and Right are to be expanded and their element types will
397 /// be checked with the same way. If we get Res != 0 on some stage, return it.
398 /// Otherwise return 0.
399 /// 6. For all other cases put llvm_unreachable.
400 int cmpType(Type *TyL, Type *TyR) const;
401
402 bool isEquivalentType(Type *Ty1, Type *Ty2) const {
403 return cmpType(Ty1, Ty2) == 0;
404 }
405
406 int cmpNumbers(uint64_t L, uint64_t R) const;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000407
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000408 int cmpAPInt(const APInt &L, const APInt &R) const;
409 int cmpAPFloat(const APFloat &L, const APFloat &R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000410 int cmpStrings(StringRef L, StringRef R) const;
411 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000412
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000413 // The two functions undergoing comparison.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000414 const Function *FnL, *FnR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000415
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000416 const DataLayout *DL;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000417
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000418 /// 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 DenseMap<const Value*, int> sn_mapL, sn_mapR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000452};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000453
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000454}
455
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000456int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
457 if (L < R) return -1;
458 if (L > R) return 1;
459 return 0;
460}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000461
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000462int FunctionComparator::cmpAPInt(const APInt &L, const APInt &R) const {
463 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
464 return Res;
465 if (L.ugt(R)) return 1;
466 if (R.ugt(L)) return -1;
467 return 0;
468}
469
470int FunctionComparator::cmpAPFloat(const APFloat &L, const APFloat &R) const {
471 if (int Res = cmpNumbers((uint64_t)&L.getSemantics(),
472 (uint64_t)&R.getSemantics()))
473 return Res;
474 return cmpAPInt(L.bitcastToAPInt(), R.bitcastToAPInt());
475}
476
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000477int FunctionComparator::cmpStrings(StringRef L, StringRef R) const {
478 // Prevent heavy comparison, compare sizes first.
479 if (int Res = cmpNumbers(L.size(), R.size()))
480 return Res;
481
482 // Compare strings lexicographically only when it is necessary: only when
483 // strings are equal in size.
484 return L.compare(R);
485}
486
487int FunctionComparator::cmpAttrs(const AttributeSet L,
488 const AttributeSet R) const {
489 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
490 return Res;
491
492 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
493 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
494 RE = R.end(i);
495 for (; LI != LE && RI != RE; ++LI, ++RI) {
496 Attribute LA = *LI;
497 Attribute RA = *RI;
498 if (LA < RA)
499 return -1;
500 if (RA < LA)
501 return 1;
502 }
503 if (LI != LE)
504 return 1;
505 if (RI != RE)
506 return -1;
507 }
508 return 0;
509}
510
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000511/// Constants comparison:
512/// 1. Check whether type of L constant could be losslessly bitcasted to R
513/// type.
514/// 2. Compare constant contents.
515/// For more details see declaration comments.
516int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
517
518 Type *TyL = L->getType();
519 Type *TyR = R->getType();
520
521 // Check whether types are bitcastable. This part is just re-factored
522 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
523 // we also pack into result which type is "less" for us.
524 int TypesRes = cmpType(TyL, TyR);
525 if (TypesRes != 0) {
526 // Types are different, but check whether we can bitcast them.
527 if (!TyL->isFirstClassType()) {
528 if (TyR->isFirstClassType())
529 return -1;
530 // Neither TyL nor TyR are values of first class type. Return the result
531 // of comparing the types
532 return TypesRes;
533 }
534 if (!TyR->isFirstClassType()) {
535 if (TyL->isFirstClassType())
536 return 1;
537 return TypesRes;
538 }
539
540 // Vector -> Vector conversions are always lossless if the two vector types
541 // have the same size, otherwise not.
542 unsigned TyLWidth = 0;
543 unsigned TyRWidth = 0;
544
545 if (const VectorType *VecTyL = dyn_cast<VectorType>(TyL))
546 TyLWidth = VecTyL->getBitWidth();
547 if (const VectorType *VecTyR = dyn_cast<VectorType>(TyR))
548 TyRWidth = VecTyR->getBitWidth();
549
550 if (TyLWidth != TyRWidth)
551 return cmpNumbers(TyLWidth, TyRWidth);
552
553 // Zero bit-width means neither TyL nor TyR are vectors.
554 if (!TyLWidth) {
555 PointerType *PTyL = dyn_cast<PointerType>(TyL);
556 PointerType *PTyR = dyn_cast<PointerType>(TyR);
557 if (PTyL && PTyR) {
558 unsigned AddrSpaceL = PTyL->getAddressSpace();
559 unsigned AddrSpaceR = PTyR->getAddressSpace();
560 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
561 return Res;
562 }
563 if (PTyL)
564 return 1;
565 if (PTyR)
566 return -1;
567
568 // TyL and TyR aren't vectors, nor pointers. We don't know how to
569 // bitcast them.
570 return TypesRes;
571 }
572 }
573
574 // OK, types are bitcastable, now check constant contents.
575
576 if (L->isNullValue() && R->isNullValue())
577 return TypesRes;
578 if (L->isNullValue() && !R->isNullValue())
579 return 1;
580 if (!L->isNullValue() && R->isNullValue())
581 return -1;
582
583 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
584 return Res;
585
586 switch (L->getValueID()) {
587 case Value::UndefValueVal: return TypesRes;
588 case Value::ConstantIntVal: {
589 const APInt &LInt = cast<ConstantInt>(L)->getValue();
590 const APInt &RInt = cast<ConstantInt>(R)->getValue();
591 return cmpAPInt(LInt, RInt);
592 }
593 case Value::ConstantFPVal: {
594 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
595 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
596 return cmpAPFloat(LAPF, RAPF);
597 }
598 case Value::ConstantArrayVal: {
599 const ConstantArray *LA = cast<ConstantArray>(L);
600 const ConstantArray *RA = cast<ConstantArray>(R);
601 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
602 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
603 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
604 return Res;
605 for (uint64_t i = 0; i < NumElementsL; ++i) {
606 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
607 cast<Constant>(RA->getOperand(i))))
608 return Res;
609 }
610 return 0;
611 }
612 case Value::ConstantStructVal: {
613 const ConstantStruct *LS = cast<ConstantStruct>(L);
614 const ConstantStruct *RS = cast<ConstantStruct>(R);
615 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
616 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
617 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
618 return Res;
619 for (unsigned i = 0; i != NumElementsL; ++i) {
620 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
621 cast<Constant>(RS->getOperand(i))))
622 return Res;
623 }
624 return 0;
625 }
626 case Value::ConstantVectorVal: {
627 const ConstantVector *LV = cast<ConstantVector>(L);
628 const ConstantVector *RV = cast<ConstantVector>(R);
629 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
630 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
631 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
632 return Res;
633 for (uint64_t i = 0; i < NumElementsL; ++i) {
634 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
635 cast<Constant>(RV->getOperand(i))))
636 return Res;
637 }
638 return 0;
639 }
640 case Value::ConstantExprVal: {
641 const ConstantExpr *LE = cast<ConstantExpr>(L);
642 const ConstantExpr *RE = cast<ConstantExpr>(R);
643 unsigned NumOperandsL = LE->getNumOperands();
644 unsigned NumOperandsR = RE->getNumOperands();
645 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
646 return Res;
647 for (unsigned i = 0; i < NumOperandsL; ++i) {
648 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
649 cast<Constant>(RE->getOperand(i))))
650 return Res;
651 }
652 return 0;
653 }
654 case Value::FunctionVal:
655 case Value::GlobalVariableVal:
656 case Value::GlobalAliasVal:
657 default: // Unknown constant, cast L and R pointers to numbers and compare.
658 return cmpNumbers((uint64_t)L, (uint64_t)R);
659 }
660}
661
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000662/// cmpType - compares two types,
663/// defines total ordering among the types set.
664/// See method declaration comments for more details.
665int FunctionComparator::cmpType(Type *TyL, Type *TyR) const {
666
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000667 PointerType *PTyL = dyn_cast<PointerType>(TyL);
668 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000669
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000670 if (DL) {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000671 if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL);
672 if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000673 }
674
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000675 if (TyL == TyR)
676 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000677
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000678 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
679 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000680
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000681 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000682 default:
683 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000684 // Fall through in Release mode.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000685 case Type::IntegerTyID:
Nick Lewyckyfb622f92011-01-26 08:50:18 +0000686 case Type::VectorTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000687 // TyL == TyR would have returned true earlier.
688 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000689
Nick Lewyckye04dc222009-06-12 08:04:51 +0000690 case Type::VoidTyID:
691 case Type::FloatTyID:
692 case Type::DoubleTyID:
693 case Type::X86_FP80TyID:
694 case Type::FP128TyID:
695 case Type::PPC_FP128TyID:
696 case Type::LabelTyID:
697 case Type::MetadataTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000698 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000699
Nick Lewyckye04dc222009-06-12 08:04:51 +0000700 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000701 assert(PTyL && PTyR && "Both types must be pointers here.");
702 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000703 }
704
705 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000706 StructType *STyL = cast<StructType>(TyL);
707 StructType *STyR = cast<StructType>(TyR);
708 if (STyL->getNumElements() != STyR->getNumElements())
709 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000710
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000711 if (STyL->isPacked() != STyR->isPacked())
712 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000713
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000714 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
715 if (int Res = cmpType(STyL->getElementType(i),
716 STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000717 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000718 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000719 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000720 }
721
722 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000723 FunctionType *FTyL = cast<FunctionType>(TyL);
724 FunctionType *FTyR = cast<FunctionType>(TyR);
725 if (FTyL->getNumParams() != FTyR->getNumParams())
726 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000727
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000728 if (FTyL->isVarArg() != FTyR->isVarArg())
729 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000730
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000731 if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000732 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000733
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000734 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
735 if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000736 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000737 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000738 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000739 }
740
Nick Lewycky375efe32010-07-16 06:31:12 +0000741 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000742 ArrayType *ATyL = cast<ArrayType>(TyL);
743 ArrayType *ATyR = cast<ArrayType>(TyR);
744 if (ATyL->getNumElements() != ATyR->getNumElements())
745 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
746 return cmpType(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000747 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000748 }
749}
750
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000751// Determine whether the two operations are the same except that pointer-to-A
752// and pointer-to-B are equivalent. This should be kept in sync with
753// Instruction::isSameOperationAs.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000754// Read method declaration comments for more details.
755int FunctionComparator::cmpOperation(const Instruction *L,
756 const Instruction *R) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000757 // Differences from Instruction::isSameOperationAs:
758 // * replace type comparison with calls to isEquivalentType.
759 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
760 // * because of the above, we don't test for the tail bit on calls later on
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000761 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
762 return Res;
763
764 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
765 return Res;
766
767 if (int Res = cmpType(L->getType(), R->getType()))
768 return Res;
769
770 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
771 R->getRawSubclassOptionalData()))
772 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000773
774 // We have two instructions of identical opcode and #operands. Check to see
775 // if all operands are the same type
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000776 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
777 if (int Res =
778 cmpType(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
779 return Res;
780 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000781
782 // Check special state that is a part of some instructions.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000783 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
784 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
785 return Res;
786 if (int Res =
787 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
788 return Res;
789 if (int Res =
790 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
791 return Res;
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000792 if (int Res =
793 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
794 return Res;
795 return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
796 (uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000797 }
798 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
799 if (int Res =
800 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
801 return Res;
802 if (int Res =
803 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
804 return Res;
805 if (int Res =
806 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
807 return Res;
808 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
809 }
810 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
811 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
812 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
813 if (int Res = cmpNumbers(CI->getCallingConv(),
814 cast<CallInst>(R)->getCallingConv()))
815 return Res;
816 return cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes());
817 }
818 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
819 if (int Res = cmpNumbers(CI->getCallingConv(),
820 cast<InvokeInst>(R)->getCallingConv()))
821 return Res;
822 return cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes());
823 }
824 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
825 ArrayRef<unsigned> LIndices = IVI->getIndices();
826 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
827 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
828 return Res;
829 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
830 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
831 return Res;
832 }
833 }
834 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
835 ArrayRef<unsigned> LIndices = EVI->getIndices();
836 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
837 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
838 return Res;
839 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
840 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
841 return Res;
842 }
843 }
844 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
845 if (int Res =
846 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
847 return Res;
848 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
849 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000850
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000851 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
852 if (int Res = cmpNumbers(CXI->isVolatile(),
853 cast<AtomicCmpXchgInst>(R)->isVolatile()))
854 return Res;
Tim Northover420a2162014-06-13 14:24:07 +0000855 if (int Res = cmpNumbers(CXI->isWeak(),
856 cast<AtomicCmpXchgInst>(R)->isWeak()))
857 return Res;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000858 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
859 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
860 return Res;
861 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
862 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
863 return Res;
864 return cmpNumbers(CXI->getSynchScope(),
865 cast<AtomicCmpXchgInst>(R)->getSynchScope());
866 }
867 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
868 if (int Res = cmpNumbers(RMWI->getOperation(),
869 cast<AtomicRMWInst>(R)->getOperation()))
870 return Res;
871 if (int Res = cmpNumbers(RMWI->isVolatile(),
872 cast<AtomicRMWInst>(R)->isVolatile()))
873 return Res;
874 if (int Res = cmpNumbers(RMWI->getOrdering(),
875 cast<AtomicRMWInst>(R)->getOrdering()))
876 return Res;
877 return cmpNumbers(RMWI->getSynchScope(),
878 cast<AtomicRMWInst>(R)->getSynchScope());
879 }
880 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000881}
882
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000883// Determine whether two GEP operations perform the same underlying arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000884// Read method declaration comments for more details.
885int FunctionComparator::cmpGEP(const GEPOperator *GEPL,
886 const GEPOperator *GEPR) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000887
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000888 unsigned int ASL = GEPL->getPointerAddressSpace();
889 unsigned int ASR = GEPR->getPointerAddressSpace();
890
891 if (int Res = cmpNumbers(ASL, ASR))
892 return Res;
893
894 // When we have target data, we can reduce the GEP down to the value in bytes
895 // added to the address.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000896 if (DL) {
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000897 unsigned BitWidth = DL->getPointerSizeInBits(ASL);
898 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
899 if (GEPL->accumulateConstantOffset(*DL, OffsetL) &&
900 GEPR->accumulateConstantOffset(*DL, OffsetR))
901 return cmpAPInt(OffsetL, OffsetR);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000902 }
903
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000904 if (int Res = cmpNumbers((uint64_t)GEPL->getPointerOperand()->getType(),
905 (uint64_t)GEPR->getPointerOperand()->getType()))
906 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000907
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000908 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
909 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000910
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000911 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
912 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
913 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000914 }
915
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000916 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000917}
918
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000919/// Compare two values used by the two functions under pair-wise comparison. If
920/// this is the first time the values are seen, they're added to the mapping so
921/// that we will detect mismatches on next use.
922/// See comments in declaration for more details.
923int FunctionComparator::cmpValues(const Value *L, const Value *R) {
924 // Catch self-reference case.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000925 if (L == FnL) {
926 if (R == FnR)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000927 return 0;
928 return -1;
929 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000930 if (R == FnR) {
931 if (L == FnL)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000932 return 0;
933 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +0000934 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000935
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000936 const Constant *ConstL = dyn_cast<Constant>(L);
937 const Constant *ConstR = dyn_cast<Constant>(R);
938 if (ConstL && ConstR) {
939 if (L == R)
940 return 0;
941 return cmpConstants(ConstL, ConstR);
942 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000943
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000944 if (ConstL)
945 return 1;
946 if (ConstR)
947 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000948
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000949 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
950 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
951
952 if (InlineAsmL && InlineAsmR)
953 return cmpNumbers((uint64_t)L, (uint64_t)R);
954 if (InlineAsmL)
955 return 1;
956 if (InlineAsmR)
957 return -1;
958
959 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
960 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
961
962 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000963}
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000964// Test whether two basic blocks have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000965int FunctionComparator::compare(const BasicBlock *BBL, const BasicBlock *BBR) {
966 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
967 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000968
969 do {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000970 if (int Res = cmpValues(InstL, InstR))
971 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000972
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000973 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
974 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
Nick Lewycky47b71c52009-06-13 19:09:52 +0000975
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000976 if (GEPL && !GEPR)
977 return 1;
978 if (GEPR && !GEPL)
979 return -1;
Nick Lewycky47b71c52009-06-13 19:09:52 +0000980
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000981 if (GEPL && GEPR) {
982 if (int Res =
983 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
984 return Res;
985 if (int Res = cmpGEP(GEPL, GEPR))
986 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000987 } else {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000988 if (int Res = cmpOperation(InstL, InstR))
989 return Res;
990 assert(InstL->getNumOperands() == InstR->getNumOperands());
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000991
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000992 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
993 Value *OpL = InstL->getOperand(i);
994 Value *OpR = InstR->getOperand(i);
995 if (int Res = cmpValues(OpL, OpR))
996 return Res;
997 if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
998 return Res;
999 // TODO: Already checked in cmpOperation
1000 if (int Res = cmpType(OpL->getType(), OpR->getType()))
1001 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001002 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001003 }
1004
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001005 ++InstL, ++InstR;
1006 } while (InstL != InstLE && InstR != InstRE);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001007
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001008 if (InstL != InstLE && InstR == InstRE)
1009 return 1;
1010 if (InstL == InstLE && InstR != InstRE)
1011 return -1;
1012 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001013}
1014
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001015// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001016int FunctionComparator::compare() {
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001017
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001018 sn_mapL.clear();
1019 sn_mapR.clear();
1020
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001021 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1022 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001023
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001024 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1025 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001026
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001027 if (FnL->hasGC()) {
1028 if (int Res = cmpNumbers((uint64_t)FnL->getGC(), (uint64_t)FnR->getGC()))
1029 return Res;
1030 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001031
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001032 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1033 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001034
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001035 if (FnL->hasSection()) {
1036 if (int Res = cmpStrings(FnL->getSection(), FnR->getSection()))
1037 return Res;
1038 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001039
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001040 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1041 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001042
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001043 // TODO: if it's internal and only used in direct calls, we could handle this
1044 // case too.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001045 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1046 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001047
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001048 if (int Res = cmpType(FnL->getFunctionType(), FnR->getFunctionType()))
1049 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001050
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001051 assert(FnL->arg_size() == FnR->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +00001052 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001053
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001054 // Visit the arguments so that they get enumerated in the order they're
1055 // passed in.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001056 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1057 ArgRI = FnR->arg_begin(),
1058 ArgLE = FnL->arg_end();
1059 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1060 if (cmpValues(ArgLI, ArgRI) != 0)
Nick Lewycky71972d42010-09-07 01:42:10 +00001061 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001062 }
1063
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001064 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1065 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001066 // functions, then takes each block from each terminator in order. As an
1067 // artifact, this also means that unreachable blocks are ignored.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001068 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001069 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001070
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001071 FnLBBs.push_back(&FnL->getEntryBlock());
1072 FnRBBs.push_back(&FnR->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001073
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001074 VisitedBBs.insert(FnLBBs[0]);
1075 while (!FnLBBs.empty()) {
1076 const BasicBlock *BBL = FnLBBs.pop_back_val();
1077 const BasicBlock *BBR = FnRBBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001078
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001079 if (int Res = cmpValues(BBL, BBR))
1080 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001081
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001082 if (int Res = compare(BBL, BBR))
1083 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001084
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001085 const TerminatorInst *TermL = BBL->getTerminator();
1086 const TerminatorInst *TermR = BBR->getTerminator();
1087
1088 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1089 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
1090 if (!VisitedBBs.insert(TermL->getSuccessor(i)))
Nick Lewycky2b3cbac2010-05-13 06:45:13 +00001091 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001092
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001093 FnLBBs.push_back(TermL->getSuccessor(i));
1094 FnRBBs.push_back(TermR->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001095 }
1096 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001097 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001098}
1099
Nick Lewycky564fcca2011-01-28 07:36:21 +00001100namespace {
1101
1102/// MergeFunctions finds functions which will generate identical machine code,
1103/// by considering all pointer types to be equivalent. Once identified,
1104/// MergeFunctions will fold them by replacing a call to one to a call to a
1105/// bitcast of the other.
1106///
1107class MergeFunctions : public ModulePass {
1108public:
1109 static char ID;
1110 MergeFunctions()
1111 : ModulePass(ID), HasGlobalAliases(false) {
1112 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1113 }
1114
Craig Topper3e4c6972014-03-05 09:10:37 +00001115 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001116
1117private:
1118 typedef DenseSet<ComparableFunction> FnSetType;
1119
1120 /// A work queue of functions that may have been modified and should be
1121 /// analyzed again.
1122 std::vector<WeakVH> Deferred;
1123
1124 /// Insert a ComparableFunction into the FnSet, or merge it away if it's
1125 /// equal to one that's already present.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001126 bool insert(ComparableFunction &NewF);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001127
1128 /// Remove a Function from the FnSet and queue it up for a second sweep of
1129 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001130 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001131
1132 /// Find the functions that use this Value and remove them from FnSet and
1133 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001134 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001135
1136 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1137 /// necessary to make types match.
1138 void replaceDirectCallers(Function *Old, Function *New);
1139
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001140 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1141 /// be converted into a thunk. In either case, it should never be visited
1142 /// again.
1143 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001144
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001145 /// Replace G with a thunk or an alias to F. Deletes G.
1146 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001147
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001148 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1149 /// of G with bitcast(F). Deletes G.
1150 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001151
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001152 /// Replace G with an alias to F. Deletes G.
1153 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001154
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001155 /// The set of all distinct functions. Use the insert() and remove() methods
1156 /// to modify it.
Nick Lewycky564fcca2011-01-28 07:36:21 +00001157 FnSetType FnSet;
1158
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001159 /// DataLayout for more accurate GEP comparisons. May be NULL.
Rafael Espindola43b5a512014-02-25 14:24:11 +00001160 const DataLayout *DL;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001161
1162 /// Whether or not the target supports global aliases.
1163 bool HasGlobalAliases;
1164};
1165
1166} // end anonymous namespace
1167
1168char MergeFunctions::ID = 0;
1169INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1170
1171ModulePass *llvm::createMergeFunctionsPass() {
1172 return new MergeFunctions();
1173}
1174
1175bool MergeFunctions::runOnModule(Module &M) {
1176 bool Changed = false;
Rafael Espindola93512512014-02-25 17:30:31 +00001177 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +00001178 DL = DLP ? &DLP->getDataLayout() : nullptr;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001179
1180 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1181 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
1182 Deferred.push_back(WeakVH(I));
1183 }
1184 FnSet.resize(Deferred.size());
1185
1186 do {
1187 std::vector<WeakVH> Worklist;
1188 Deferred.swap(Worklist);
1189
1190 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1191 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1192
1193 // Insert only strong functions and merge them. Strong function merging
1194 // always deletes one of them.
1195 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1196 E = Worklist.end(); I != E; ++I) {
1197 if (!*I) continue;
1198 Function *F = cast<Function>(*I);
1199 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1200 !F->mayBeOverridden()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001201 ComparableFunction CF = ComparableFunction(F, DL);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001202 Changed |= insert(CF);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001203 }
1204 }
1205
1206 // Insert only weak functions and merge them. By doing these second we
1207 // create thunks to the strong function when possible. When two weak
1208 // functions are identical, we create a new strong function with two weak
1209 // weak thunks to it which are identical but not mergable.
1210 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1211 E = Worklist.end(); I != E; ++I) {
1212 if (!*I) continue;
1213 Function *F = cast<Function>(*I);
1214 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1215 F->mayBeOverridden()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001216 ComparableFunction CF = ComparableFunction(F, DL);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001217 Changed |= insert(CF);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001218 }
1219 }
1220 DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n');
1221 } while (!Deferred.empty());
1222
1223 FnSet.clear();
1224
1225 return Changed;
1226}
1227
1228bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS,
1229 const ComparableFunction &RHS) {
1230 if (LHS.getFunc() == RHS.getFunc() &&
1231 LHS.getHash() == RHS.getHash())
1232 return true;
1233 if (!LHS.getFunc() || !RHS.getFunc())
1234 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001235
1236 // One of these is a special "underlying pointer comparison only" object.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001237 if (LHS.getDataLayout() == ComparableFunction::LookupOnly ||
1238 RHS.getDataLayout() == ComparableFunction::LookupOnly)
Nick Lewycky292e78c2011-02-09 06:32:02 +00001239 return false;
1240
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001241 assert(LHS.getDataLayout() == RHS.getDataLayout() &&
Nick Lewycky564fcca2011-01-28 07:36:21 +00001242 "Comparing functions for different targets");
1243
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001244 return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(), RHS.getFunc())
1245 .compare() == 0;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001246}
1247
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001248// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001249void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1250 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001251 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1252 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001253 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001254 CallSite CS(U->getUser());
1255 if (CS && CS.isCallee(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001256 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001257 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001258 }
1259 }
1260}
1261
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001262// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1263void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001264 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1265 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1266 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001267 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001268 return;
1269 }
1270 }
1271
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001272 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001273}
1274
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001275// Helper for writeThunk,
1276// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001277// but a bit simpler then CastInst::getCastOpcode.
Carlo Kok307625c2014-04-30 17:53:04 +00001278static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001279 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001280 if (SrcTy->isStructTy()) {
1281 assert(DestTy->isStructTy());
1282 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1283 Value *Result = UndefValue::get(DestTy);
1284 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1285 Value *Element = createCast(
1286 Builder, Builder.CreateExtractValue(V, ArrayRef<unsigned int>(I)),
1287 DestTy->getStructElementType(I));
1288
1289 Result =
1290 Builder.CreateInsertValue(Result, Element, ArrayRef<unsigned int>(I));
1291 }
1292 return Result;
1293 }
1294 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001295 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1296 return Builder.CreateIntToPtr(V, DestTy);
1297 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1298 return Builder.CreatePtrToInt(V, DestTy);
1299 else
1300 return Builder.CreateBitCast(V, DestTy);
1301}
1302
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001303// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1304// of G with bitcast(F). Deletes G.
1305void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001306 if (!G->mayBeOverridden()) {
1307 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001308 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001309 }
1310
Nick Lewycky71972d42010-09-07 01:42:10 +00001311 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001312 // stop here and delete G. There's no need for a thunk.
1313 if (G->hasLocalLinkage() && G->use_empty()) {
1314 G->eraseFromParent();
1315 return;
1316 }
1317
Nick Lewycky25675ac2009-06-12 15:56:56 +00001318 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1319 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001320 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001321 IRBuilder<false> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001322
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001323 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001324 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001325 FunctionType *FFTy = F->getFunctionType();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001326 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1327 AI != AE; ++AI) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001328 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001329 ++i;
1330 }
1331
Jay Foad5bd375a2011-07-15 08:37:34 +00001332 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001333 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001334 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001335 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001336 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001337 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001338 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001339 }
1340
1341 NewG->copyAttributesFrom(G);
1342 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001343 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001344 G->replaceAllUsesWith(NewG);
1345 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001346
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001347 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001348 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001349}
1350
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001351// Replace G with an alias to F and delete G.
1352void MergeFunctions::writeAlias(Function *F, Function *G) {
Rafael Espindola4fe00942014-05-16 13:34:04 +00001353 PointerType *PTy = G->getType();
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00001354 auto *GA = GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1355 G->getLinkage(), "", F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001356 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1357 GA->takeName(G);
1358 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001359 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001360 G->replaceAllUsesWith(GA);
1361 G->eraseFromParent();
1362
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001363 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001364 ++NumAliasesWritten;
1365}
1366
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001367// Merge two equivalent functions. Upon completion, Function G is deleted.
1368void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky71972d42010-09-07 01:42:10 +00001369 if (F->mayBeOverridden()) {
1370 assert(G->mayBeOverridden());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001371
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001372 if (HasGlobalAliases) {
1373 // Make them both thunks to the same internal function.
1374 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1375 F->getParent());
1376 H->copyAttributesFrom(F);
1377 H->takeName(F);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001378 removeUsers(F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001379 F->replaceAllUsesWith(H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001380
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001381 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
Nick Lewyckyf0067b62010-08-09 21:03:28 +00001382
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001383 writeAlias(F, G);
1384 writeAlias(F, H);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001385
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001386 F->setAlignment(MaxAlignment);
1387 F->setLinkage(GlobalValue::PrivateLinkage);
1388 } else {
1389 // We can't merge them. Instead, pick one and update all direct callers
1390 // to call it and hope that we improve the instruction cache hit rate.
1391 replaceDirectCallers(G, F);
1392 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001393
1394 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001395 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001396 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001397 }
1398
Nick Lewyckye04dc222009-06-12 08:04:51 +00001399 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001400}
1401
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001402// Insert a ComparableFunction into the FnSet, or merge it away if equal to one
1403// that was already inserted.
1404bool MergeFunctions::insert(ComparableFunction &NewF) {
Nick Lewycky00959372010-09-05 08:22:49 +00001405 std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
Nick Lewycky292e78c2011-02-09 06:32:02 +00001406 if (Result.second) {
1407 DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001408 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001409 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001410
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +00001411 const ComparableFunction &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001412
Matt Arsenault517d84e2013-10-01 18:05:30 +00001413 // Don't merge tiny functions, since it can just end up making the function
1414 // larger.
1415 // FIXME: Should still merge them if they are unnamed_addr and produce an
1416 // alias.
1417 if (NewF.getFunc()->size() == 1) {
1418 if (NewF.getFunc()->front().size() <= 2) {
1419 DEBUG(dbgs() << NewF.getFunc()->getName()
1420 << " is to small to bother merging\n");
1421 return false;
1422 }
1423 }
1424
Nick Lewycky00959372010-09-05 08:22:49 +00001425 // Never thunk a strong function to a weak function.
Nick Lewycky71972d42010-09-07 01:42:10 +00001426 assert(!OldF.getFunc()->mayBeOverridden() ||
1427 NewF.getFunc()->mayBeOverridden());
Nick Lewycky00959372010-09-05 08:22:49 +00001428
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +00001429 DEBUG(dbgs() << " " << OldF.getFunc()->getName() << " == "
1430 << NewF.getFunc()->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001431
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +00001432 Function *DeleteF = NewF.getFunc();
1433 NewF.release();
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001434 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001435 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001436}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001437
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001438// Remove a function from FnSet. If it was already in FnSet, add it to Deferred
1439// so that we'll look at it in the next round.
1440void MergeFunctions::remove(Function *F) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001441 // We need to make sure we remove F, not a function "equal" to F per the
1442 // function equality comparator.
1443 //
1444 // The special "lookup only" ComparableFunction bypasses the expensive
1445 // function comparison in favour of a pointer comparison on the underlying
1446 // Function*'s.
1447 ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
Nick Lewycky4e250c82011-01-02 02:46:33 +00001448 if (FnSet.erase(CF)) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001449 DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n");
Nick Lewycky4e250c82011-01-02 02:46:33 +00001450 Deferred.push_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001451 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001452}
Nick Lewycky00959372010-09-05 08:22:49 +00001453
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001454// For each instruction used by the value, remove() the function that contains
1455// the instruction. This should happen right before a call to RAUW.
1456void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001457 std::vector<Value *> Worklist;
1458 Worklist.push_back(V);
1459 while (!Worklist.empty()) {
1460 Value *V = Worklist.back();
1461 Worklist.pop_back();
1462
Chandler Carruthcdf47882014-03-09 03:16:01 +00001463 for (User *U : V->users()) {
1464 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001465 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001466 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001467 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001468 } else if (Constant *C = dyn_cast<Constant>(U)) {
1469 for (User *UU : C->users())
1470 Worklist.push_back(UU);
Nick Lewycky5361b842011-01-02 19:16:44 +00001471 }
Nick Lewycky00959372010-09-05 08:22:49 +00001472 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001473 }
Nick Lewycky00959372010-09-05 08:22:49 +00001474}