blob: 2030c22e0f7ca335233150b51e0f1dc223e4fe23 [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//
Stepan Dyatkovskiy471eab32014-06-22 00:57:09 +000012// 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).
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000022//
Stepan Dyatkovskiy471eab32014-06-22 00:57:09 +000023// 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.
JF Bastien5e4303d2015-08-15 01:18:18 +000030//
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.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000038//
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000039// 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.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000042//
43//===----------------------------------------------------------------------===//
44//
45// Future work:
46//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000047// * virtual functions.
48//
49// Many functions have their address taken by the virtual function table for
50// the object they belong to. However, as long as it's only used for a lookup
Nick Lewyckyfbd27572010-08-08 05:04:23 +000051// and call, this is irrelevant, and we'd like to fold such functions.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000052//
Nick Lewyckyfbd27572010-08-08 05:04:23 +000053// * be smarter about bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000054//
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
Nick Lewyckyfbd27572010-08-08 05:04:23 +000058// other doesn't. We should learn to look through bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000059//
Stepan Dyatkovskiy471eab32014-06-22 00:57:09 +000060// * Compare complex types with pointer types inside.
61// * Compare cross-reference cases.
62// * Compare complex expressions.
63//
64// All the three issues above could be described as ability to prove that
65// fA == fB == fC == fE == fF == fG in example below:
66//
67// void fA() {
68// fB();
69// }
70// void fB() {
71// fA();
72// }
73//
74// void fE() {
75// fF();
76// }
77// void fF() {
78// fG();
79// }
80// void fG() {
81// fE();
82// }
83//
84// Simplest cross-reference case (fA <--> fB) was implemented in previous
85// versions of MergeFunctions, though it presented only in two function pairs
86// in test-suite (that counts >50k functions)
87// Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
88// could cover much more cases.
89//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000090//===----------------------------------------------------------------------===//
91
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000092#include "llvm/Transforms/IPO.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000093#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"
JF Bastien5e4303d2015-08-15 01:18:18 +000098#include "llvm/ADT/Hashing.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000099#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000100#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"
Chandler Carruth4220e9c2014-03-04 11:17:44 +0000108#include "llvm/IR/ValueHandle.h"
JF Bastien057292a2015-08-21 23:27:24 +0000109#include "llvm/IR/ValueMap.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000110#include "llvm/Pass.h"
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000111#include "llvm/Support/CommandLine.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000112#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +0000113#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000114#include "llvm/Support/raw_ostream.h"
Nick Lewycky68984ed2010-08-31 08:29:37 +0000115#include <vector>
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000116
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000117using namespace llvm;
118
Chandler Carruth964daaa2014-04-22 02:55:47 +0000119#define DEBUG_TYPE "mergefunc"
120
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000121STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +0000122STATISTIC(NumThunksWritten, "Number of thunks generated");
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000123STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky71972d42010-09-07 01:42:10 +0000124STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000125
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000126static cl::opt<unsigned> NumFunctionsForSanityCheck(
127 "mergefunc-sanity",
128 cl::desc("How many functions in module could be used for "
129 "MergeFunctions pass sanity check. "
130 "'0' disables this check. Works only with '-debug' key."),
131 cl::init(0), cl::Hidden);
132
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000133namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000134
JF Bastien057292a2015-08-21 23:27:24 +0000135/// GlobalNumberState assigns an integer to each global value in the program,
136/// which is used by the comparison routine to order references to globals. This
137/// state must be preserved throughout the pass, because Functions and other
138/// globals need to maintain their relative order. Globals are assigned a number
139/// when they are first visited. This order is deterministic, and so the
140/// assigned numbers are as well. When two functions are merged, neither number
141/// is updated. If the symbols are weak, this would be incorrect. If they are
142/// strong, then one will be replaced at all references to the other, and so
143/// direct callsites will now see one or the other symbol, and no update is
144/// necessary. Note that if we were guaranteed unique names, we could just
145/// compare those, but this would not work for stripped bitcodes or for those
146/// few symbols without a name.
147class GlobalNumberState {
148 struct Config : ValueMapConfig<GlobalValue*> {
149 enum { FollowRAUW = false };
150 };
151 // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW
152 // occurs, the mapping does not change. Tracking changes is unnecessary, and
153 // also problematic for weak symbols (which may be overwritten).
154 typedef ValueMap<GlobalValue *, uint64_t, Config> ValueNumberMap;
155 ValueNumberMap GlobalNumbers;
156 // The next unused serial number to assign to a global.
157 uint64_t NextNumber;
158 public:
159 GlobalNumberState() : GlobalNumbers(), NextNumber(0) {}
160 uint64_t getNumber(GlobalValue* Global) {
161 ValueNumberMap::iterator MapIter;
162 bool Inserted;
163 std::tie(MapIter, Inserted) = GlobalNumbers.insert({Global, NextNumber});
164 if (Inserted)
165 NextNumber++;
166 return MapIter->second;
167 }
Arnold Schwaighofer0591c5d2015-10-05 17:26:36 +0000168 void clear() {
169 GlobalNumbers.clear();
170 }
JF Bastien057292a2015-08-21 23:27:24 +0000171};
172
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000173/// FunctionComparator - Compares two functions to determine whether or not
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000174/// they will generate machine code with the same behaviour. DataLayout is
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000175/// used if available. The comparator always fails conservatively (erring on the
176/// side of claiming that two functions are different).
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000177class FunctionComparator {
178public:
JF Bastien057292a2015-08-21 23:27:24 +0000179 FunctionComparator(const Function *F1, const Function *F2,
180 GlobalNumberState* GN)
181 : FnL(F1), FnR(F2), GlobalNumbers(GN) {}
Nick Lewyckye04dc222009-06-12 08:04:51 +0000182
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000183 /// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000184 int compare();
JF Bastien5e4303d2015-08-15 01:18:18 +0000185 /// Hash a function. Equivalent functions will have the same hash, and unequal
186 /// functions will have different hashes with high probability.
187 typedef uint64_t FunctionHash;
188 static FunctionHash functionHash(Function &);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000189
190private:
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000191 /// Test whether two basic blocks have equivalent behaviour.
JF Bastien057292a2015-08-21 23:27:24 +0000192 int cmpBasicBlocks(const BasicBlock *BBL, const BasicBlock *BBR);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000193
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000194 /// Constants comparison.
195 /// Its analog to lexicographical comparison between hypothetical numbers
196 /// of next format:
197 /// <bitcastability-trait><raw-bit-contents>
198 ///
199 /// 1. Bitcastability.
200 /// Check whether L's type could be losslessly bitcasted to R's type.
201 /// On this stage method, in case when lossless bitcast is not possible
202 /// method returns -1 or 1, thus also defining which type is greater in
203 /// context of bitcastability.
204 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
205 /// to the contents comparison.
206 /// If types differ, remember types comparison result and check
207 /// whether we still can bitcast types.
208 /// Stage 1: Types that satisfies isFirstClassType conditions are always
209 /// greater then others.
210 /// Stage 2: Vector is greater then non-vector.
211 /// If both types are vectors, then vector with greater bitwidth is
212 /// greater.
213 /// If both types are vectors with the same bitwidth, then types
214 /// are bitcastable, and we can skip other stages, and go to contents
215 /// comparison.
216 /// Stage 3: Pointer types are greater than non-pointers. If both types are
217 /// pointers of the same address space - go to contents comparison.
218 /// Different address spaces: pointer with greater address space is
219 /// greater.
220 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
221 /// We don't know how to bitcast them. So, we better don't do it,
222 /// and return types comparison result (so it determines the
223 /// relationship among constants we don't know how to bitcast).
224 ///
225 /// Just for clearance, let's see how the set of constants could look
226 /// on single dimension axis:
227 ///
228 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
229 /// Where: NFCT - Not a FirstClassType
230 /// FCT - FirstClassTyp:
231 ///
232 /// 2. Compare raw contents.
233 /// It ignores types on this stage and only compares bits from L and R.
234 /// Returns 0, if L and R has equivalent contents.
235 /// -1 or 1 if values are different.
236 /// Pretty trivial:
237 /// 2.1. If contents are numbers, compare numbers.
238 /// Ints with greater bitwidth are greater. Ints with same bitwidths
239 /// compared by their contents.
240 /// 2.2. "And so on". Just to avoid discrepancies with comments
241 /// perhaps it would be better to read the implementation itself.
242 /// 3. And again about overall picture. Let's look back at how the ordered set
243 /// of constants will look like:
244 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
245 ///
246 /// Now look, what could be inside [FCT, "others"], for example:
247 /// [FCT, "others"] =
248 /// [
249 /// [double 0.1], [double 1.23],
250 /// [i32 1], [i32 2],
251 /// { double 1.0 }, ; StructTyID, NumElements = 1
252 /// { i32 1 }, ; StructTyID, NumElements = 1
253 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
254 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
255 /// ]
256 ///
257 /// Let's explain the order. Float numbers will be less than integers, just
258 /// because of cmpType terms: FloatTyID < IntegerTyID.
259 /// Floats (with same fltSemantics) are sorted according to their value.
260 /// Then you can see integers, and they are, like a floats,
261 /// could be easy sorted among each others.
262 /// The structures. Structures are grouped at the tail, again because of their
263 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
264 /// Structures with greater number of elements are greater. Structures with
265 /// greater elements going first are greater.
266 /// The same logic with vectors, arrays and other possible complex types.
267 ///
268 /// Bitcastable constants.
269 /// Let's assume, that some constant, belongs to some group of
270 /// "so-called-equal" values with different types, and at the same time
271 /// belongs to another group of constants with equal types
272 /// and "really" equal values.
273 ///
274 /// Now, prove that this is impossible:
275 ///
276 /// If constant A with type TyA is bitcastable to B with type TyB, then:
277 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
278 /// those should be vectors (if TyA is vector), pointers
279 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
280 /// be equal to TyB.
281 /// 2. All constants with non-equal, but bitcastable types to TyA, are
282 /// bitcastable to B.
283 /// Once again, just because we allow it to vectors and pointers only.
284 /// This statement could be expanded as below:
285 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
286 /// vector B, and thus bitcastable to B as well.
287 /// 2.2. All pointers of the same address space, no matter what they point to,
288 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
289 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
290 /// QED.
291 ///
292 /// In another words, for pointers and vectors, we ignore top-level type and
293 /// look at their particular properties (bit-width for vectors, and
294 /// address space for pointers).
295 /// If these properties are equal - compare their contents.
296 int cmpConstants(const Constant *L, const Constant *R);
297
JF Bastien057292a2015-08-21 23:27:24 +0000298 /// Compares two global values by number. Uses the GlobalNumbersState to
299 /// identify the same gobals across function calls.
300 int cmpGlobalValues(GlobalValue *L, GlobalValue *R);
301
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000302 /// Assign or look up previously assigned numbers for the two values, and
303 /// return whether the numbers are equal. Numbers are assigned in the order
304 /// visited.
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000305 /// Comparison order:
306 /// Stage 0: Value that is function itself is always greater then others.
307 /// If left and right values are references to their functions, then
308 /// they are equal.
309 /// Stage 1: Constants are greater than non-constants.
310 /// If both left and right are constants, then the result of
311 /// cmpConstants is used as cmpValues result.
312 /// Stage 2: InlineAsm instances are greater than others. If both left and
313 /// right are InlineAsm instances, InlineAsm* pointers casted to
314 /// integers and compared as numbers.
315 /// Stage 3: For all other cases we compare order we meet these values in
316 /// their functions. If right value was met first during scanning,
317 /// then left value is greater.
318 /// In another words, we compare serial numbers, for more details
319 /// see comments for sn_mapL and sn_mapR.
320 int cmpValues(const Value *L, const Value *R);
321
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000322 /// Compare two Instructions for equivalence, similar to
323 /// Instruction::isSameOperationAs but with modifications to the type
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000324 /// comparison.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000325 /// Stages are listed in "most significant stage first" order:
326 /// On each stage below, we do comparison between some left and right
327 /// operation parts. If parts are non-equal, we assign parts comparison
328 /// result to the operation comparison result and exit from method.
329 /// Otherwise we proceed to the next stage.
330 /// Stages:
331 /// 1. Operations opcodes. Compared as numbers.
332 /// 2. Number of operands.
333 /// 3. Operation types. Compared with cmpType method.
334 /// 4. Compare operation subclass optional data as stream of bytes:
335 /// just convert it to integers and call cmpNumbers.
336 /// 5. Compare in operation operand types with cmpType in
337 /// most significant operand first order.
338 /// 6. Last stage. Check operations for some specific attributes.
339 /// For example, for Load it would be:
340 /// 6.1.Load: volatile (as boolean flag)
341 /// 6.2.Load: alignment (as integer numbers)
342 /// 6.3.Load: synch-scope (as integer numbers)
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000343 /// 6.4.Load: range metadata (as integer numbers)
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000344 /// On this stage its better to see the code, since its not more than 10-15
345 /// strings for particular instruction, and could change sometimes.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000346 int cmpOperations(const Instruction *L, const Instruction *R) const;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000347
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000348 /// Compare two GEPs for equivalent pointer arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000349 /// Parts to be compared for each comparison stage,
350 /// most significant stage first:
351 /// 1. Address space. As numbers.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000352 /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000353 /// 3. Pointer operand type (using cmpType method).
354 /// 4. Number of operands.
355 /// 5. Compare operands, using cmpValues method.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000356 int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR);
357 int cmpGEPs(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
358 return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000359 }
360
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000361 /// cmpType - compares two types,
362 /// defines total ordering among the types set.
363 ///
364 /// Return values:
365 /// 0 if types are equal,
366 /// -1 if Left is less than Right,
367 /// +1 if Left is greater than Right.
368 ///
369 /// Description:
370 /// Comparison is broken onto stages. Like in lexicographical comparison
371 /// stage coming first has higher priority.
372 /// On each explanation stage keep in mind total ordering properties.
373 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000374 /// 0. Before comparison we coerce pointer types of 0 address space to
375 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000376 /// We also don't bother with same type at left and right, so
377 /// just return 0 in this case.
378 ///
379 /// 1. If types are of different kind (different type IDs).
380 /// Return result of type IDs comparison, treating them as numbers.
JF Bastien057292a2015-08-21 23:27:24 +0000381 /// 2. If types are integers, check that they have the same width. If they
382 /// are vectors, check that they have the same count and subtype.
383 /// 3. Types have the same ID, so check whether they are one of:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000384 /// * Void
385 /// * Float
386 /// * Double
387 /// * X86_FP80
388 /// * FP128
389 /// * PPC_FP128
390 /// * Label
391 /// * Metadata
JF Bastien057292a2015-08-21 23:27:24 +0000392 /// We can treat these types as equal whenever their IDs are same.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000393 /// 4. If Left and Right are pointers, return result of address space
394 /// comparison (numbers comparison). We can treat pointer types of same
395 /// address space as equal.
396 /// 5. If types are complex.
397 /// Then both Left and Right are to be expanded and their element types will
398 /// be checked with the same way. If we get Res != 0 on some stage, return it.
399 /// Otherwise return 0.
400 /// 6. For all other cases put llvm_unreachable.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000401 int cmpTypes(Type *TyL, Type *TyR) const;
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000402
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000403 int cmpNumbers(uint64_t L, uint64_t R) const;
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000404 int cmpAPInts(const APInt &L, const APInt &R) const;
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000405 int cmpAPFloats(const APFloat &L, const APFloat &R) const;
JF Bastien057292a2015-08-21 23:27:24 +0000406 int cmpInlineAsm(const InlineAsm *L, const InlineAsm *R) const;
407 int cmpMem(StringRef L, StringRef R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000408 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000409 int cmpRangeMetadata(const MDNode* L, const MDNode* R) const;
Sanjoy Das2a74eb02015-12-14 19:11:40 +0000410 int cmpOperandBundlesSchema(const Instruction *L, const Instruction *R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000411
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000412 // The two functions undergoing comparison.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000413 const Function *FnL, *FnR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000414
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000415 /// Assign serial numbers to values from left function, and values from
416 /// right function.
417 /// Explanation:
418 /// Being comparing functions we need to compare values we meet at left and
419 /// right sides.
420 /// Its easy to sort things out for external values. It just should be
421 /// the same value at left and right.
422 /// But for local values (those were introduced inside function body)
423 /// we have to ensure they were introduced at exactly the same place,
424 /// and plays the same role.
425 /// Let's assign serial number to each value when we meet it first time.
426 /// Values that were met at same place will be with same serial numbers.
427 /// In this case it would be good to explain few points about values assigned
428 /// to BBs and other ways of implementation (see below).
429 ///
430 /// 1. Safety of BB reordering.
431 /// It's safe to change the order of BasicBlocks in function.
432 /// Relationship with other functions and serial numbering will not be
433 /// changed in this case.
434 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
435 /// from the entry, and then take each terminator. So it doesn't matter how in
436 /// fact BBs are ordered in function. And since cmpValues are called during
437 /// this walk, the numbering depends only on how BBs located inside the CFG.
438 /// So the answer is - yes. We will get the same numbering.
439 ///
440 /// 2. Impossibility to use dominance properties of values.
441 /// If we compare two instruction operands: first is usage of local
442 /// variable AL from function FL, and second is usage of local variable AR
443 /// from FR, we could compare their origins and check whether they are
444 /// defined at the same place.
445 /// But, we are still not able to compare operands of PHI nodes, since those
446 /// could be operands from further BBs we didn't scan yet.
447 /// So it's impossible to use dominance properties in general.
448 DenseMap<const Value*, int> sn_mapL, sn_mapR;
JF Bastien057292a2015-08-21 23:27:24 +0000449
450 // The global state we will use
451 GlobalNumberState* GlobalNumbers;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000452};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000453
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000454class FunctionNode {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000455 mutable AssertingVH<Function> F;
JF Bastien5e4303d2015-08-15 01:18:18 +0000456 FunctionComparator::FunctionHash Hash;
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000457public:
JF Bastien5e4303d2015-08-15 01:18:18 +0000458 // Note the hash is recalculated potentially multiple times, but it is cheap.
JF Bastien057292a2015-08-21 23:27:24 +0000459 FunctionNode(Function *F)
460 : F(F), Hash(FunctionComparator::functionHash(*F)) {}
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000461 Function *getFunc() const { return F; }
JF Bastien057292a2015-08-21 23:27:24 +0000462 FunctionComparator::FunctionHash getHash() const { return Hash; }
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000463
464 /// Replace the reference to the function F by the function G, assuming their
465 /// implementations are equal.
466 void replaceBy(Function *G) const {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000467 F = G;
468 }
469
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000470 void release() { F = nullptr; }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000471};
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000472} // end anonymous namespace
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000473
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000474int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
475 if (L < R) return -1;
476 if (L > R) return 1;
477 return 0;
478}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000479
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000480int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000481 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
482 return Res;
483 if (L.ugt(R)) return 1;
484 if (R.ugt(L)) return -1;
485 return 0;
486}
487
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000488int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000489 // Floats are ordered first by semantics (i.e. float, double, half, etc.),
490 // then by value interpreted as a bitstring (aka APInt).
JF Bastien057292a2015-08-21 23:27:24 +0000491 const fltSemantics &SL = L.getSemantics(), &SR = R.getSemantics();
492 if (int Res = cmpNumbers(APFloat::semanticsPrecision(SL),
493 APFloat::semanticsPrecision(SR)))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000494 return Res;
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000495 if (int Res = cmpNumbers(APFloat::semanticsMaxExponent(SL),
496 APFloat::semanticsMaxExponent(SR)))
497 return Res;
498 if (int Res = cmpNumbers(APFloat::semanticsMinExponent(SL),
499 APFloat::semanticsMinExponent(SR)))
500 return Res;
501 if (int Res = cmpNumbers(APFloat::semanticsSizeInBits(SL),
502 APFloat::semanticsSizeInBits(SR)))
503 return Res;
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000504 return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000505}
506
JF Bastien057292a2015-08-21 23:27:24 +0000507int FunctionComparator::cmpMem(StringRef L, StringRef R) const {
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000508 // Prevent heavy comparison, compare sizes first.
509 if (int Res = cmpNumbers(L.size(), R.size()))
510 return Res;
511
512 // Compare strings lexicographically only when it is necessary: only when
513 // strings are equal in size.
514 return L.compare(R);
515}
516
517int FunctionComparator::cmpAttrs(const AttributeSet L,
518 const AttributeSet R) const {
519 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
520 return Res;
521
522 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
523 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
524 RE = R.end(i);
525 for (; LI != LE && RI != RE; ++LI, ++RI) {
526 Attribute LA = *LI;
527 Attribute RA = *RI;
528 if (LA < RA)
529 return -1;
530 if (RA < LA)
531 return 1;
532 }
533 if (LI != LE)
534 return 1;
535 if (RI != RE)
536 return -1;
537 }
538 return 0;
539}
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000540
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000541int FunctionComparator::cmpRangeMetadata(const MDNode* L,
542 const MDNode* R) const {
543 if (L == R)
544 return 0;
545 if (!L)
546 return -1;
547 if (!R)
548 return 1;
549 // Range metadata is a sequence of numbers. Make sure they are the same
550 // sequence.
551 // TODO: Note that as this is metadata, it is possible to drop and/or merge
552 // this data when considering functions to merge. Thus this comparison would
553 // return 0 (i.e. equivalent), but merging would become more complicated
554 // because the ranges would need to be unioned. It is not likely that
555 // functions differ ONLY in this metadata if they are actually the same
556 // function semantically.
557 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
558 return Res;
559 for (size_t I = 0; I < L->getNumOperands(); ++I) {
560 ConstantInt* LLow = mdconst::extract<ConstantInt>(L->getOperand(I));
561 ConstantInt* RLow = mdconst::extract<ConstantInt>(R->getOperand(I));
562 if (int Res = cmpAPInts(LLow->getValue(), RLow->getValue()))
563 return Res;
564 }
565 return 0;
566}
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000567
Sanjoy Das2a74eb02015-12-14 19:11:40 +0000568int FunctionComparator::cmpOperandBundlesSchema(const Instruction *L,
569 const Instruction *R) const {
570 ImmutableCallSite LCS(L);
571 ImmutableCallSite RCS(R);
572
573 assert(LCS && RCS && "Must be calls or invokes!");
574 assert(LCS.isCall() == RCS.isCall() && "Can't compare otherwise!");
575
576 if (int Res =
577 cmpNumbers(LCS.getNumOperandBundles(), RCS.getNumOperandBundles()))
578 return Res;
579
580 for (unsigned i = 0, e = LCS.getNumOperandBundles(); i != e; ++i) {
581 auto OBL = LCS.getOperandBundleAt(i);
582 auto OBR = RCS.getOperandBundleAt(i);
583
584 if (int Res = OBL.getTagName().compare(OBR.getTagName()))
585 return Res;
586
587 if (int Res = cmpNumbers(OBL.Inputs.size(), OBR.Inputs.size()))
588 return Res;
589 }
590
591 return 0;
592}
593
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000594/// Constants comparison:
595/// 1. Check whether type of L constant could be losslessly bitcasted to R
596/// type.
597/// 2. Compare constant contents.
598/// For more details see declaration comments.
599int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
600
601 Type *TyL = L->getType();
602 Type *TyR = R->getType();
603
604 // Check whether types are bitcastable. This part is just re-factored
605 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
606 // we also pack into result which type is "less" for us.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000607 int TypesRes = cmpTypes(TyL, TyR);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000608 if (TypesRes != 0) {
609 // Types are different, but check whether we can bitcast them.
610 if (!TyL->isFirstClassType()) {
611 if (TyR->isFirstClassType())
612 return -1;
613 // Neither TyL nor TyR are values of first class type. Return the result
614 // of comparing the types
615 return TypesRes;
616 }
617 if (!TyR->isFirstClassType()) {
618 if (TyL->isFirstClassType())
619 return 1;
620 return TypesRes;
621 }
622
623 // Vector -> Vector conversions are always lossless if the two vector types
624 // have the same size, otherwise not.
625 unsigned TyLWidth = 0;
626 unsigned TyRWidth = 0;
627
Craig Toppere3dcce92015-08-01 22:20:21 +0000628 if (auto *VecTyL = dyn_cast<VectorType>(TyL))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000629 TyLWidth = VecTyL->getBitWidth();
Craig Toppere3dcce92015-08-01 22:20:21 +0000630 if (auto *VecTyR = dyn_cast<VectorType>(TyR))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000631 TyRWidth = VecTyR->getBitWidth();
632
633 if (TyLWidth != TyRWidth)
634 return cmpNumbers(TyLWidth, TyRWidth);
635
636 // Zero bit-width means neither TyL nor TyR are vectors.
637 if (!TyLWidth) {
638 PointerType *PTyL = dyn_cast<PointerType>(TyL);
639 PointerType *PTyR = dyn_cast<PointerType>(TyR);
640 if (PTyL && PTyR) {
641 unsigned AddrSpaceL = PTyL->getAddressSpace();
642 unsigned AddrSpaceR = PTyR->getAddressSpace();
643 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
644 return Res;
645 }
646 if (PTyL)
647 return 1;
648 if (PTyR)
649 return -1;
650
651 // TyL and TyR aren't vectors, nor pointers. We don't know how to
652 // bitcast them.
653 return TypesRes;
654 }
655 }
656
657 // OK, types are bitcastable, now check constant contents.
658
659 if (L->isNullValue() && R->isNullValue())
660 return TypesRes;
661 if (L->isNullValue() && !R->isNullValue())
662 return 1;
663 if (!L->isNullValue() && R->isNullValue())
664 return -1;
665
JF Bastien057292a2015-08-21 23:27:24 +0000666 auto GlobalValueL = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(L));
667 auto GlobalValueR = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(R));
668 if (GlobalValueL && GlobalValueR) {
669 return cmpGlobalValues(GlobalValueL, GlobalValueR);
670 }
671
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000672 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
673 return Res;
674
JF Bastien057292a2015-08-21 23:27:24 +0000675 if (const auto *SeqL = dyn_cast<ConstantDataSequential>(L)) {
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000676 const auto *SeqR = cast<ConstantDataSequential>(R);
JF Bastien057292a2015-08-21 23:27:24 +0000677 // This handles ConstantDataArray and ConstantDataVector. Note that we
678 // compare the two raw data arrays, which might differ depending on the host
679 // endianness. This isn't a problem though, because the endiness of a module
680 // will affect the order of the constants, but this order is the same
681 // for a given input module and host platform.
682 return cmpMem(SeqL->getRawDataValues(), SeqR->getRawDataValues());
683 }
684
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000685 switch (L->getValueID()) {
David Majnemerf0f224d2015-11-11 21:57:16 +0000686 case Value::UndefValueVal:
687 case Value::ConstantTokenNoneVal:
688 return TypesRes;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000689 case Value::ConstantIntVal: {
690 const APInt &LInt = cast<ConstantInt>(L)->getValue();
691 const APInt &RInt = cast<ConstantInt>(R)->getValue();
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000692 return cmpAPInts(LInt, RInt);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000693 }
694 case Value::ConstantFPVal: {
695 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
696 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000697 return cmpAPFloats(LAPF, RAPF);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000698 }
699 case Value::ConstantArrayVal: {
700 const ConstantArray *LA = cast<ConstantArray>(L);
701 const ConstantArray *RA = cast<ConstantArray>(R);
702 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
703 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
704 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
705 return Res;
706 for (uint64_t i = 0; i < NumElementsL; ++i) {
707 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
708 cast<Constant>(RA->getOperand(i))))
709 return Res;
710 }
711 return 0;
712 }
713 case Value::ConstantStructVal: {
714 const ConstantStruct *LS = cast<ConstantStruct>(L);
715 const ConstantStruct *RS = cast<ConstantStruct>(R);
716 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
717 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
718 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
719 return Res;
720 for (unsigned i = 0; i != NumElementsL; ++i) {
721 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
722 cast<Constant>(RS->getOperand(i))))
723 return Res;
724 }
725 return 0;
726 }
727 case Value::ConstantVectorVal: {
728 const ConstantVector *LV = cast<ConstantVector>(L);
729 const ConstantVector *RV = cast<ConstantVector>(R);
730 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
731 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
732 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
733 return Res;
734 for (uint64_t i = 0; i < NumElementsL; ++i) {
735 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
736 cast<Constant>(RV->getOperand(i))))
737 return Res;
738 }
739 return 0;
740 }
741 case Value::ConstantExprVal: {
742 const ConstantExpr *LE = cast<ConstantExpr>(L);
743 const ConstantExpr *RE = cast<ConstantExpr>(R);
744 unsigned NumOperandsL = LE->getNumOperands();
745 unsigned NumOperandsR = RE->getNumOperands();
746 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
747 return Res;
748 for (unsigned i = 0; i < NumOperandsL; ++i) {
749 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
750 cast<Constant>(RE->getOperand(i))))
751 return Res;
752 }
753 return 0;
754 }
JF Bastien057292a2015-08-21 23:27:24 +0000755 case Value::BlockAddressVal: {
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000756 const BlockAddress *LBA = cast<BlockAddress>(L);
757 const BlockAddress *RBA = cast<BlockAddress>(R);
758 if (int Res = cmpValues(LBA->getFunction(), RBA->getFunction()))
759 return Res;
760 if (LBA->getFunction() == RBA->getFunction()) {
761 // They are BBs in the same function. Order by which comes first in the
762 // BB order of the function. This order is deterministic.
763 Function* F = LBA->getFunction();
764 BasicBlock *LBB = LBA->getBasicBlock();
765 BasicBlock *RBB = RBA->getBasicBlock();
766 if (LBB == RBB)
767 return 0;
768 for(BasicBlock &BB : F->getBasicBlockList()) {
769 if (&BB == LBB) {
770 assert(&BB != RBB);
771 return -1;
772 }
773 if (&BB == RBB)
774 return 1;
775 }
776 llvm_unreachable("Basic Block Address does not point to a basic block in "
777 "its function.");
778 return -1;
779 } else {
780 // cmpValues said the functions are the same. So because they aren't
781 // literally the same pointer, they must respectively be the left and
782 // right functions.
783 assert(LBA->getFunction() == FnL && RBA->getFunction() == FnR);
784 // cmpValues will tell us if these are equivalent BasicBlocks, in the
785 // context of their respective functions.
786 return cmpValues(LBA->getBasicBlock(), RBA->getBasicBlock());
787 }
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000788 }
JF Bastien057292a2015-08-21 23:27:24 +0000789 default: // Unknown constant, abort.
790 DEBUG(dbgs() << "Looking at valueID " << L->getValueID() << "\n");
791 llvm_unreachable("Constant ValueID not recognized.");
792 return -1;
793 }
794}
795
796int FunctionComparator::cmpGlobalValues(GlobalValue *L, GlobalValue* R) {
797 return cmpNumbers(GlobalNumbers->getNumber(L), GlobalNumbers->getNumber(R));
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000798}
799
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000800/// cmpType - compares two types,
801/// defines total ordering among the types set.
802/// See method declaration comments for more details.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000803int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000804 PointerType *PTyL = dyn_cast<PointerType>(TyL);
805 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000806
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000807 const DataLayout &DL = FnL->getParent()->getDataLayout();
808 if (PTyL && PTyL->getAddressSpace() == 0)
809 TyL = DL.getIntPtrType(TyL);
810 if (PTyR && PTyR->getAddressSpace() == 0)
811 TyR = DL.getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000812
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000813 if (TyL == TyR)
814 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000815
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000816 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
817 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000818
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000819 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000820 default:
821 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000822 // Fall through in Release mode.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000823 case Type::IntegerTyID:
JF Bastien057292a2015-08-21 23:27:24 +0000824 return cmpNumbers(cast<IntegerType>(TyL)->getBitWidth(),
825 cast<IntegerType>(TyR)->getBitWidth());
826 case Type::VectorTyID: {
827 VectorType *VTyL = cast<VectorType>(TyL), *VTyR = cast<VectorType>(TyR);
828 if (int Res = cmpNumbers(VTyL->getNumElements(), VTyR->getNumElements()))
829 return Res;
830 return cmpTypes(VTyL->getElementType(), VTyR->getElementType());
831 }
832 // TyL == TyR would have returned true earlier, because types are uniqued.
Nick Lewyckye04dc222009-06-12 08:04:51 +0000833 case Type::VoidTyID:
834 case Type::FloatTyID:
835 case Type::DoubleTyID:
836 case Type::X86_FP80TyID:
837 case Type::FP128TyID:
838 case Type::PPC_FP128TyID:
839 case Type::LabelTyID:
840 case Type::MetadataTyID:
David Majnemerb611e3f2015-08-14 05:09:07 +0000841 case Type::TokenTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000842 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000843
Nick Lewyckye04dc222009-06-12 08:04:51 +0000844 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000845 assert(PTyL && PTyR && "Both types must be pointers here.");
846 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000847 }
848
849 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000850 StructType *STyL = cast<StructType>(TyL);
851 StructType *STyR = cast<StructType>(TyR);
852 if (STyL->getNumElements() != STyR->getNumElements())
853 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000854
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000855 if (STyL->isPacked() != STyR->isPacked())
856 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000857
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000858 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000859 if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000860 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000861 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000862 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000863 }
864
865 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000866 FunctionType *FTyL = cast<FunctionType>(TyL);
867 FunctionType *FTyR = cast<FunctionType>(TyR);
868 if (FTyL->getNumParams() != FTyR->getNumParams())
869 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000870
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000871 if (FTyL->isVarArg() != FTyR->isVarArg())
872 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000873
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000874 if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000875 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000876
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000877 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000878 if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000879 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000880 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000881 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000882 }
883
Nick Lewycky375efe32010-07-16 06:31:12 +0000884 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000885 ArrayType *ATyL = cast<ArrayType>(TyL);
886 ArrayType *ATyR = cast<ArrayType>(TyR);
887 if (ATyL->getNumElements() != ATyR->getNumElements())
888 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000889 return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000890 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000891 }
892}
893
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000894// Determine whether the two operations are the same except that pointer-to-A
895// and pointer-to-B are equivalent. This should be kept in sync with
896// Instruction::isSameOperationAs.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000897// Read method declaration comments for more details.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000898int FunctionComparator::cmpOperations(const Instruction *L,
899 const Instruction *R) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000900 // Differences from Instruction::isSameOperationAs:
901 // * replace type comparison with calls to isEquivalentType.
902 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
903 // * because of the above, we don't test for the tail bit on calls later on
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000904 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
905 return Res;
906
907 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
908 return Res;
909
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000910 if (int Res = cmpTypes(L->getType(), R->getType()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000911 return Res;
912
913 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
914 R->getRawSubclassOptionalData()))
915 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000916
Arnold Schwaighofer6a8c5f62015-05-12 21:42:22 +0000917 if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
918 if (int Res = cmpTypes(AI->getAllocatedType(),
919 cast<AllocaInst>(R)->getAllocatedType()))
920 return Res;
921 if (int Res =
922 cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment()))
923 return Res;
924 }
925
Nick Lewyckye04dc222009-06-12 08:04:51 +0000926 // We have two instructions of identical opcode and #operands. Check to see
927 // if all operands are the same type
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000928 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
929 if (int Res =
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000930 cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000931 return Res;
932 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000933
934 // Check special state that is a part of some instructions.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000935 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
936 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
937 return Res;
938 if (int Res =
939 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
940 return Res;
941 if (int Res =
942 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
943 return Res;
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000944 if (int Res =
945 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
946 return Res;
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000947 return cmpRangeMetadata(LI->getMetadata(LLVMContext::MD_range),
948 cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000949 }
950 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
951 if (int Res =
952 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
953 return Res;
954 if (int Res =
955 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
956 return Res;
957 if (int Res =
958 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
959 return Res;
960 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
961 }
962 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
963 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
964 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
965 if (int Res = cmpNumbers(CI->getCallingConv(),
966 cast<CallInst>(R)->getCallingConv()))
967 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000968 if (int Res =
969 cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
970 return Res;
Sanjoy Das2a74eb02015-12-14 19:11:40 +0000971 if (int Res = cmpOperandBundlesSchema(CI, R))
972 return Res;
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000973 return cmpRangeMetadata(
974 CI->getMetadata(LLVMContext::MD_range),
975 cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000976 }
Sanjoy Dasadfec012015-12-14 19:11:45 +0000977 if (const InvokeInst *II = dyn_cast<InvokeInst>(L)) {
978 if (int Res = cmpNumbers(II->getCallingConv(),
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000979 cast<InvokeInst>(R)->getCallingConv()))
980 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000981 if (int Res =
Sanjoy Dasadfec012015-12-14 19:11:45 +0000982 cmpAttrs(II->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000983 return Res;
Sanjoy Dasadfec012015-12-14 19:11:45 +0000984 if (int Res = cmpOperandBundlesSchema(II, R))
Sanjoy Das2a74eb02015-12-14 19:11:40 +0000985 return Res;
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000986 return cmpRangeMetadata(
Sanjoy Dasadfec012015-12-14 19:11:45 +0000987 II->getMetadata(LLVMContext::MD_range),
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000988 cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000989 }
990 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
991 ArrayRef<unsigned> LIndices = IVI->getIndices();
992 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
993 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
994 return Res;
995 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
996 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
997 return Res;
998 }
999 }
1000 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
1001 ArrayRef<unsigned> LIndices = EVI->getIndices();
1002 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
1003 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
1004 return Res;
1005 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
1006 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
1007 return Res;
1008 }
1009 }
1010 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
1011 if (int Res =
1012 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
1013 return Res;
1014 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
1015 }
Nick Lewyckye04dc222009-06-12 08:04:51 +00001016
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +00001017 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
1018 if (int Res = cmpNumbers(CXI->isVolatile(),
1019 cast<AtomicCmpXchgInst>(R)->isVolatile()))
1020 return Res;
Tim Northover420a2162014-06-13 14:24:07 +00001021 if (int Res = cmpNumbers(CXI->isWeak(),
1022 cast<AtomicCmpXchgInst>(R)->isWeak()))
1023 return Res;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +00001024 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
1025 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
1026 return Res;
1027 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
1028 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
1029 return Res;
1030 return cmpNumbers(CXI->getSynchScope(),
1031 cast<AtomicCmpXchgInst>(R)->getSynchScope());
1032 }
1033 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
1034 if (int Res = cmpNumbers(RMWI->getOperation(),
1035 cast<AtomicRMWInst>(R)->getOperation()))
1036 return Res;
1037 if (int Res = cmpNumbers(RMWI->isVolatile(),
1038 cast<AtomicRMWInst>(R)->isVolatile()))
1039 return Res;
1040 if (int Res = cmpNumbers(RMWI->getOrdering(),
1041 cast<AtomicRMWInst>(R)->getOrdering()))
1042 return Res;
1043 return cmpNumbers(RMWI->getSynchScope(),
1044 cast<AtomicRMWInst>(R)->getSynchScope());
1045 }
1046 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001047}
1048
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001049// Determine whether two GEP operations perform the same underlying arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001050// Read method declaration comments for more details.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +00001051int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001052 const GEPOperator *GEPR) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +00001053
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001054 unsigned int ASL = GEPL->getPointerAddressSpace();
1055 unsigned int ASR = GEPR->getPointerAddressSpace();
1056
1057 if (int Res = cmpNumbers(ASL, ASR))
1058 return Res;
1059
1060 // When we have target data, we can reduce the GEP down to the value in bytes
1061 // added to the address.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001062 const DataLayout &DL = FnL->getParent()->getDataLayout();
1063 unsigned BitWidth = DL.getPointerSizeInBits(ASL);
1064 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
1065 if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
1066 GEPR->accumulateConstantOffset(DL, OffsetR))
1067 return cmpAPInts(OffsetL, OffsetR);
JF Bastien26aca142015-09-14 15:37:48 +00001068 if (int Res = cmpTypes(GEPL->getSourceElementType(),
1069 GEPR->getSourceElementType()))
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001070 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001071
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001072 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
1073 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001074
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001075 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
1076 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
1077 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001078 }
1079
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001080 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001081}
1082
JF Bastien057292a2015-08-21 23:27:24 +00001083int FunctionComparator::cmpInlineAsm(const InlineAsm *L,
1084 const InlineAsm *R) const {
1085 // InlineAsm's are uniqued. If they are the same pointer, obviously they are
1086 // the same, otherwise compare the fields.
1087 if (L == R)
1088 return 0;
1089 if (int Res = cmpTypes(L->getFunctionType(), R->getFunctionType()))
1090 return Res;
1091 if (int Res = cmpMem(L->getAsmString(), R->getAsmString()))
1092 return Res;
1093 if (int Res = cmpMem(L->getConstraintString(), R->getConstraintString()))
1094 return Res;
1095 if (int Res = cmpNumbers(L->hasSideEffects(), R->hasSideEffects()))
1096 return Res;
1097 if (int Res = cmpNumbers(L->isAlignStack(), R->isAlignStack()))
1098 return Res;
1099 if (int Res = cmpNumbers(L->getDialect(), R->getDialect()))
1100 return Res;
1101 llvm_unreachable("InlineAsm blocks were not uniqued.");
1102 return 0;
1103}
1104
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001105/// Compare two values used by the two functions under pair-wise comparison. If
1106/// this is the first time the values are seen, they're added to the mapping so
1107/// that we will detect mismatches on next use.
1108/// See comments in declaration for more details.
1109int FunctionComparator::cmpValues(const Value *L, const Value *R) {
1110 // Catch self-reference case.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001111 if (L == FnL) {
1112 if (R == FnR)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001113 return 0;
1114 return -1;
1115 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001116 if (R == FnR) {
1117 if (L == FnL)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001118 return 0;
1119 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +00001120 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001121
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001122 const Constant *ConstL = dyn_cast<Constant>(L);
1123 const Constant *ConstR = dyn_cast<Constant>(R);
1124 if (ConstL && ConstR) {
1125 if (L == R)
1126 return 0;
1127 return cmpConstants(ConstL, ConstR);
1128 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001129
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001130 if (ConstL)
1131 return 1;
1132 if (ConstR)
1133 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001134
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001135 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
1136 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
1137
1138 if (InlineAsmL && InlineAsmR)
JF Bastien057292a2015-08-21 23:27:24 +00001139 return cmpInlineAsm(InlineAsmL, InlineAsmR);
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001140 if (InlineAsmL)
1141 return 1;
1142 if (InlineAsmR)
1143 return -1;
1144
1145 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
1146 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
1147
1148 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001149}
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001150// Test whether two basic blocks have equivalent behaviour.
JF Bastien057292a2015-08-21 23:27:24 +00001151int FunctionComparator::cmpBasicBlocks(const BasicBlock *BBL,
1152 const BasicBlock *BBR) {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001153 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
1154 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001155
1156 do {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001157 if (int Res = cmpValues(&*InstL, &*InstR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001158 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001159
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001160 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
1161 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
Nick Lewycky47b71c52009-06-13 19:09:52 +00001162
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001163 if (GEPL && !GEPR)
1164 return 1;
1165 if (GEPR && !GEPL)
1166 return -1;
Nick Lewycky47b71c52009-06-13 19:09:52 +00001167
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001168 if (GEPL && GEPR) {
1169 if (int Res =
1170 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
1171 return Res;
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +00001172 if (int Res = cmpGEPs(GEPL, GEPR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001173 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001174 } else {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001175 if (int Res = cmpOperations(&*InstL, &*InstR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001176 return Res;
1177 assert(InstL->getNumOperands() == InstR->getNumOperands());
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001178
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001179 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
1180 Value *OpL = InstL->getOperand(i);
1181 Value *OpR = InstR->getOperand(i);
1182 if (int Res = cmpValues(OpL, OpR))
1183 return Res;
JF Bastien9dc042a2015-08-26 03:02:58 +00001184 // cmpValues should ensure this is true.
1185 assert(cmpTypes(OpL->getType(), OpR->getType()) == 0);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001186 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001187 }
1188
Richard Trieu7a083812016-02-18 22:09:30 +00001189 ++InstL;
1190 ++InstR;
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001191 } while (InstL != InstLE && InstR != InstRE);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001192
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001193 if (InstL != InstLE && InstR == InstRE)
1194 return 1;
1195 if (InstL == InstLE && InstR != InstRE)
1196 return -1;
1197 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001198}
1199
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001200// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001201int FunctionComparator::compare() {
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001202 sn_mapL.clear();
1203 sn_mapR.clear();
1204
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001205 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1206 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001207
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001208 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1209 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001210
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001211 if (FnL->hasGC()) {
JF Bastien057292a2015-08-21 23:27:24 +00001212 if (int Res = cmpMem(FnL->getGC(), FnR->getGC()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001213 return Res;
1214 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001215
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001216 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1217 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001218
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001219 if (FnL->hasSection()) {
JF Bastien057292a2015-08-21 23:27:24 +00001220 if (int Res = cmpMem(FnL->getSection(), FnR->getSection()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001221 return Res;
1222 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001223
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001224 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1225 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001226
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001227 // TODO: if it's internal and only used in direct calls, we could handle this
1228 // case too.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001229 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1230 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001231
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +00001232 if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001233 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001234
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001235 assert(FnL->arg_size() == FnR->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +00001236 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001237
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001238 // Visit the arguments so that they get enumerated in the order they're
1239 // passed in.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001240 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1241 ArgRI = FnR->arg_begin(),
1242 ArgLE = FnL->arg_end();
1243 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001244 if (cmpValues(&*ArgLI, &*ArgRI) != 0)
Nick Lewycky71972d42010-09-07 01:42:10 +00001245 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001246 }
1247
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001248 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1249 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001250 // functions, then takes each block from each terminator in order. As an
1251 // artifact, this also means that unreachable blocks are ignored.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001252 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
Matthias Braunb30f2f512016-01-30 01:24:31 +00001253 SmallPtrSet<const BasicBlock *, 32> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001254
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001255 FnLBBs.push_back(&FnL->getEntryBlock());
1256 FnRBBs.push_back(&FnR->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001257
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001258 VisitedBBs.insert(FnLBBs[0]);
1259 while (!FnLBBs.empty()) {
1260 const BasicBlock *BBL = FnLBBs.pop_back_val();
1261 const BasicBlock *BBR = FnRBBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001262
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001263 if (int Res = cmpValues(BBL, BBR))
1264 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001265
JF Bastien057292a2015-08-21 23:27:24 +00001266 if (int Res = cmpBasicBlocks(BBL, BBR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001267 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001268
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001269 const TerminatorInst *TermL = BBL->getTerminator();
1270 const TerminatorInst *TermR = BBR->getTerminator();
1271
1272 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1273 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
David Blaikie70573dc2014-11-19 07:49:26 +00001274 if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
Nick Lewycky2b3cbac2010-05-13 06:45:13 +00001275 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001276
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001277 FnLBBs.push_back(TermL->getSuccessor(i));
1278 FnRBBs.push_back(TermR->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001279 }
1280 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001281 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001282}
1283
Benjamin Kramer83709b12015-11-16 09:01:28 +00001284namespace {
JF Bastien5e4303d2015-08-15 01:18:18 +00001285// Accumulate the hash of a sequence of 64-bit integers. This is similar to a
1286// hash of a sequence of 64bit ints, but the entire input does not need to be
1287// available at once. This interface is necessary for functionHash because it
1288// needs to accumulate the hash as the structure of the function is traversed
1289// without saving these values to an intermediate buffer. This form of hashing
1290// is not often needed, as usually the object to hash is just read from a
1291// buffer.
1292class HashAccumulator64 {
1293 uint64_t Hash;
1294public:
1295 // Initialize to random constant, so the state isn't zero.
1296 HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
1297 void add(uint64_t V) {
1298 Hash = llvm::hashing::detail::hash_16_bytes(Hash, V);
1299 }
1300 // No finishing is required, because the entire hash value is used.
1301 uint64_t getHash() { return Hash; }
1302};
Benjamin Kramer83709b12015-11-16 09:01:28 +00001303} // end anonymous namespace
JF Bastien5e4303d2015-08-15 01:18:18 +00001304
1305// A function hash is calculated by considering only the number of arguments and
1306// whether a function is varargs, the order of basic blocks (given by the
1307// successors of each basic block in depth first order), and the order of
1308// opcodes of each instruction within each of these basic blocks. This mirrors
1309// the strategy compare() uses to compare functions by walking the BBs in depth
1310// first order and comparing each instruction in sequence. Because this hash
1311// does not look at the operands, it is insensitive to things such as the
1312// target of calls and the constants used in the function, which makes it useful
1313// when possibly merging functions which are the same modulo constants and call
1314// targets.
1315FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
1316 HashAccumulator64 H;
1317 H.add(F.isVarArg());
1318 H.add(F.arg_size());
1319
1320 SmallVector<const BasicBlock *, 8> BBs;
1321 SmallSet<const BasicBlock *, 16> VisitedBBs;
1322
JF Bastien057292a2015-08-21 23:27:24 +00001323 // Walk the blocks in the same order as FunctionComparator::cmpBasicBlocks(),
JF Bastien5e4303d2015-08-15 01:18:18 +00001324 // accumulating the hash of the function "structure." (BB and opcode sequence)
1325 BBs.push_back(&F.getEntryBlock());
1326 VisitedBBs.insert(BBs[0]);
1327 while (!BBs.empty()) {
1328 const BasicBlock *BB = BBs.pop_back_val();
1329 // This random value acts as a block header, as otherwise the partition of
1330 // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
1331 H.add(45798);
1332 for (auto &Inst : *BB) {
1333 H.add(Inst.getOpcode());
1334 }
1335 const TerminatorInst *Term = BB->getTerminator();
1336 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
1337 if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
1338 continue;
1339 BBs.push_back(Term->getSuccessor(i));
1340 }
1341 }
1342 return H.getHash();
1343}
1344
1345
Nick Lewycky564fcca2011-01-28 07:36:21 +00001346namespace {
1347
1348/// MergeFunctions finds functions which will generate identical machine code,
1349/// by considering all pointer types to be equivalent. Once identified,
1350/// MergeFunctions will fold them by replacing a call to one to a call to a
1351/// bitcast of the other.
1352///
1353class MergeFunctions : public ModulePass {
1354public:
1355 static char ID;
1356 MergeFunctions()
JF Bastien3a4ad612015-09-02 23:55:23 +00001357 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)), FNodesInTree(),
JF Bastien057292a2015-08-21 23:27:24 +00001358 HasGlobalAliases(false) {
Nick Lewycky564fcca2011-01-28 07:36:21 +00001359 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1360 }
1361
Craig Topper3e4c6972014-03-05 09:10:37 +00001362 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001363
1364private:
JF Bastien057292a2015-08-21 23:27:24 +00001365 // The function comparison operator is provided here so that FunctionNodes do
1366 // not need to become larger with another pointer.
1367 class FunctionNodeCmp {
1368 GlobalNumberState* GlobalNumbers;
1369 public:
1370 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
1371 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
1372 // Order first by hashes, then full function comparison.
1373 if (LHS.getHash() != RHS.getHash())
1374 return LHS.getHash() < RHS.getHash();
1375 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
1376 return FCmp.compare() == -1;
1377 }
1378 };
1379 typedef std::set<FunctionNode, FunctionNodeCmp> FnTreeType;
1380
1381 GlobalNumberState GlobalNumbers;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001382
1383 /// A work queue of functions that may have been modified and should be
1384 /// analyzed again.
1385 std::vector<WeakVH> Deferred;
1386
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001387 /// Checks the rules of order relation introduced among functions set.
1388 /// Returns true, if sanity check has been passed, and false if failed.
1389 bool doSanityCheck(std::vector<WeakVH> &Worklist);
1390
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001391 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +00001392 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001393 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001394
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001395 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +00001396 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001397 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001398
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001399 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +00001400 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001401 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001402
1403 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1404 /// necessary to make types match.
1405 void replaceDirectCallers(Function *Old, Function *New);
1406
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001407 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1408 /// be converted into a thunk. In either case, it should never be visited
1409 /// again.
1410 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001411
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001412 /// Replace G with a thunk or an alias to F. Deletes G.
1413 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001414
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001415 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1416 /// of G with bitcast(F). Deletes G.
1417 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001418
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001419 /// Replace G with an alias to F. Deletes G.
1420 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001421
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001422 /// Replace function F with function G in the function tree.
JF Bastien3a4ad612015-09-02 23:55:23 +00001423 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001424
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001425 /// The set of all distinct functions. Use the insert() and remove() methods
JF Bastien3a4ad612015-09-02 23:55:23 +00001426 /// to modify it. The map allows efficient lookup and deferring of Functions.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001427 FnTreeType FnTree;
JF Bastien3a4ad612015-09-02 23:55:23 +00001428 // Map functions to the iterators of the FunctionNode which contains them
1429 // in the FnTree. This must be updated carefully whenever the FnTree is
1430 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
1431 // dangling iterators into FnTree. The invariant that preserves this is that
1432 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
1433 ValueMap<Function*, FnTreeType::iterator> FNodesInTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001434
Nick Lewycky564fcca2011-01-28 07:36:21 +00001435 /// Whether or not the target supports global aliases.
1436 bool HasGlobalAliases;
1437};
1438
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001439} // end anonymous namespace
Nick Lewycky564fcca2011-01-28 07:36:21 +00001440
1441char MergeFunctions::ID = 0;
1442INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1443
1444ModulePass *llvm::createMergeFunctionsPass() {
1445 return new MergeFunctions();
1446}
1447
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001448bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1449 if (const unsigned Max = NumFunctionsForSanityCheck) {
1450 unsigned TripleNumber = 0;
1451 bool Valid = true;
1452
1453 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1454
1455 unsigned i = 0;
1456 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1457 I != E && i < Max; ++I, ++i) {
1458 unsigned j = i;
1459 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1460 Function *F1 = cast<Function>(*I);
1461 Function *F2 = cast<Function>(*J);
JF Bastien057292a2015-08-21 23:27:24 +00001462 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
1463 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001464
1465 // If F1 <= F2, then F2 >= F1, otherwise report failure.
1466 if (Res1 != -Res2) {
1467 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1468 << "\n";
1469 F1->dump();
1470 F2->dump();
1471 Valid = false;
1472 }
1473
1474 if (Res1 == 0)
1475 continue;
1476
1477 unsigned k = j;
1478 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1479 ++k, ++K, ++TripleNumber) {
1480 if (K == J)
1481 continue;
1482
1483 Function *F3 = cast<Function>(*K);
JF Bastien057292a2015-08-21 23:27:24 +00001484 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
1485 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001486
1487 bool Transitive = true;
1488
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001489 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001490 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001491 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001492 } else if (Res3 != 0 && Res3 == -Res4) {
1493 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001494 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001495 } else if (Res4 != 0 && -Res3 == Res4) {
1496 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001497 Transitive = Res4 == -Res1;
1498 }
1499
1500 if (!Transitive) {
1501 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1502 << TripleNumber << "\n";
1503 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1504 << Res4 << "\n";
1505 F1->dump();
1506 F2->dump();
1507 F3->dump();
1508 Valid = false;
1509 }
1510 }
1511 }
1512 }
1513
1514 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1515 return Valid;
1516 }
1517 return true;
1518}
1519
Nick Lewycky564fcca2011-01-28 07:36:21 +00001520bool MergeFunctions::runOnModule(Module &M) {
1521 bool Changed = false;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001522
JF Bastien5e4303d2015-08-15 01:18:18 +00001523 // All functions in the module, ordered by hash. Functions with a unique
1524 // hash value are easily eliminated.
1525 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
1526 HashedFuncs;
1527 for (Function &Func : M) {
1528 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
1529 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
1530 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001531 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001532
NAKAMURA Takumi51962752015-08-16 02:41:23 +00001533 std::stable_sort(
1534 HashedFuncs.begin(), HashedFuncs.end(),
1535 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
1536 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
1537 return a.first < b.first;
1538 });
JF Bastien5e4303d2015-08-15 01:18:18 +00001539
1540 auto S = HashedFuncs.begin();
1541 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
1542 // If the hash value matches the previous value or the next one, we must
1543 // consider merging it. Otherwise it is dropped and never considered again.
1544 if ((I != S && std::prev(I)->first == I->first) ||
1545 (std::next(I) != IE && std::next(I)->first == I->first) ) {
1546 Deferred.push_back(WeakVH(I->second));
1547 }
1548 }
1549
Nick Lewycky564fcca2011-01-28 07:36:21 +00001550 do {
1551 std::vector<WeakVH> Worklist;
1552 Deferred.swap(Worklist);
1553
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001554 DEBUG(doSanityCheck(Worklist));
1555
Nick Lewycky564fcca2011-01-28 07:36:21 +00001556 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1557 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1558
1559 // Insert only strong functions and merge them. Strong function merging
1560 // always deletes one of them.
1561 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1562 E = Worklist.end(); I != E; ++I) {
1563 if (!*I) continue;
1564 Function *F = cast<Function>(*I);
1565 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1566 !F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001567 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001568 }
1569 }
1570
1571 // Insert only weak functions and merge them. By doing these second we
1572 // create thunks to the strong function when possible. When two weak
1573 // functions are identical, we create a new strong function with two weak
1574 // weak thunks to it which are identical but not mergable.
1575 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1576 E = Worklist.end(); I != E; ++I) {
1577 if (!*I) continue;
1578 Function *F = cast<Function>(*I);
1579 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1580 F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001581 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001582 }
1583 }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001584 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +00001585 } while (!Deferred.empty());
1586
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001587 FnTree.clear();
Arnold Schwaighofer0591c5d2015-10-05 17:26:36 +00001588 GlobalNumbers.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +00001589
1590 return Changed;
1591}
1592
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001593// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001594void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1595 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001596 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1597 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001598 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001599 CallSite CS(U->getUser());
1600 if (CS && CS.isCallee(U)) {
Arnold Schwaighofer36512332015-07-21 17:07:07 +00001601 // Transfer the called function's attributes to the call site. Due to the
JF Bastienfa946232015-09-10 18:08:35 +00001602 // bitcast we will 'lose' ABI changing attributes because the 'called
Arnold Schwaighofer36512332015-07-21 17:07:07 +00001603 // function' is no longer a Function* but the bitcast. Code that looks up
1604 // the attributes from the called function will fail.
JF Bastienfa946232015-09-10 18:08:35 +00001605
1606 // FIXME: This is not actually true, at least not anymore. The callsite
1607 // will always have the same ABI affecting attributes as the callee,
1608 // because otherwise the original input has UB. Note that Old and New
1609 // always have matching ABI, so no attributes need to be changed.
1610 // Transferring other attributes may help other optimizations, but that
1611 // should be done uniformly and not in this ad-hoc way.
Arnold Schwaighofer36512332015-07-21 17:07:07 +00001612 auto &Context = New->getContext();
1613 auto NewFuncAttrs = New->getAttributes();
1614 auto CallSiteAttrs = CS.getAttributes();
1615
1616 CallSiteAttrs = CallSiteAttrs.addAttributes(
1617 Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes());
1618
1619 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) {
1620 AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx);
1621 if (Attrs.getNumSlots())
1622 CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs);
1623 }
1624
1625 CS.setAttributes(CallSiteAttrs);
1626
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001627 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001628 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001629 }
1630 }
1631}
1632
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001633// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1634void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001635 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1636 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1637 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001638 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001639 return;
1640 }
1641 }
1642
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001643 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001644}
1645
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001646// Helper for writeThunk,
1647// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001648// but a bit simpler then CastInst::getCastOpcode.
Carlo Kok307625c2014-04-30 17:53:04 +00001649static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001650 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001651 if (SrcTy->isStructTy()) {
1652 assert(DestTy->isStructTy());
1653 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1654 Value *Result = UndefValue::get(DestTy);
1655 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1656 Value *Element = createCast(
Craig Toppere1d12942014-08-27 05:25:25 +00001657 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
Carlo Kok307625c2014-04-30 17:53:04 +00001658 DestTy->getStructElementType(I));
1659
1660 Result =
Craig Toppere1d12942014-08-27 05:25:25 +00001661 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
Carlo Kok307625c2014-04-30 17:53:04 +00001662 }
1663 return Result;
1664 }
1665 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001666 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1667 return Builder.CreateIntToPtr(V, DestTy);
1668 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1669 return Builder.CreatePtrToInt(V, DestTy);
1670 else
1671 return Builder.CreateBitCast(V, DestTy);
1672}
1673
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001674// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1675// of G with bitcast(F). Deletes G.
1676void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001677 if (!G->mayBeOverridden()) {
1678 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001679 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001680 }
1681
Nick Lewycky71972d42010-09-07 01:42:10 +00001682 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001683 // stop here and delete G. There's no need for a thunk.
1684 if (G->hasLocalLinkage() && G->use_empty()) {
1685 G->eraseFromParent();
1686 return;
1687 }
1688
Nick Lewycky25675ac2009-06-12 15:56:56 +00001689 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1690 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001691 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001692 IRBuilder<false> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001693
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001694 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001695 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001696 FunctionType *FFTy = F->getFunctionType();
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001697 for (Argument & AI : NewG->args()) {
1698 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001699 ++i;
1700 }
1701
Jay Foad5bd375a2011-07-15 08:37:34 +00001702 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001703 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001704 CI->setCallingConv(F->getCallingConv());
JF Bastienfa946232015-09-10 18:08:35 +00001705 CI->setAttributes(F->getAttributes());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001706 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001707 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001708 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001709 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001710 }
1711
1712 NewG->copyAttributesFrom(G);
1713 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001714 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001715 G->replaceAllUsesWith(NewG);
1716 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001717
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001718 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001719 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001720}
1721
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001722// Replace G with an alias to F and delete G.
1723void MergeFunctions::writeAlias(Function *F, Function *G) {
David Blaikie6614d8d2015-09-14 20:29:26 +00001724 auto *GA = GlobalAlias::create(G->getLinkage(), "", F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001725 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1726 GA->takeName(G);
1727 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001728 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001729 G->replaceAllUsesWith(GA);
1730 G->eraseFromParent();
1731
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001732 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001733 ++NumAliasesWritten;
1734}
1735
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001736// Merge two equivalent functions. Upon completion, Function G is deleted.
1737void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky71972d42010-09-07 01:42:10 +00001738 if (F->mayBeOverridden()) {
1739 assert(G->mayBeOverridden());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001740
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001741 // Make them both thunks to the same internal function.
1742 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1743 F->getParent());
1744 H->copyAttributesFrom(F);
1745 H->takeName(F);
1746 removeUsers(F);
1747 F->replaceAllUsesWith(H);
1748
1749 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1750
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001751 if (HasGlobalAliases) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001752 writeAlias(F, G);
1753 writeAlias(F, H);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001754 } else {
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001755 writeThunk(F, G);
1756 writeThunk(F, H);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001757 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001758
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001759 F->setAlignment(MaxAlignment);
1760 F->setLinkage(GlobalValue::PrivateLinkage);
Nick Lewycky71972d42010-09-07 01:42:10 +00001761 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001762 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001763 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001764 }
1765
Nick Lewyckye04dc222009-06-12 08:04:51 +00001766 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001767}
1768
JF Bastien3a4ad612015-09-02 23:55:23 +00001769/// Replace function F by function G.
1770void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001771 Function *G) {
JF Bastien3a4ad612015-09-02 23:55:23 +00001772 Function *F = FN.getFunc();
JF Bastien057292a2015-08-21 23:27:24 +00001773 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
1774 "The two functions must be equal");
JF Bastien3a4ad612015-09-02 23:55:23 +00001775
1776 auto I = FNodesInTree.find(F);
1777 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
1778 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
1779
1780 FnTreeType::iterator IterToFNInFnTree = I->second;
1781 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
1782 // Remove F -> FN and insert G -> FN
1783 FNodesInTree.erase(I);
1784 FNodesInTree.insert({G, IterToFNInFnTree});
1785 // Replace F with G in FN, which is stored inside the FnTree.
1786 FN.replaceBy(G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001787}
1788
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001789// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001790// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001791bool MergeFunctions::insert(Function *NewFunction) {
1792 std::pair<FnTreeType::iterator, bool> Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001793 FnTree.insert(FunctionNode(NewFunction));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001794
Nick Lewycky292e78c2011-02-09 06:32:02 +00001795 if (Result.second) {
JF Bastien3a4ad612015-09-02 23:55:23 +00001796 assert(FNodesInTree.count(NewFunction) == 0);
1797 FNodesInTree.insert({NewFunction, Result.first});
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001798 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001799 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001800 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001801
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +00001802 const FunctionNode &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001803
Matt Arsenault517d84e2013-10-01 18:05:30 +00001804 // Don't merge tiny functions, since it can just end up making the function
1805 // larger.
1806 // FIXME: Should still merge them if they are unnamed_addr and produce an
1807 // alias.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001808 if (NewFunction->size() == 1) {
1809 if (NewFunction->front().size() <= 2) {
1810 DEBUG(dbgs() << NewFunction->getName()
1811 << " is to small to bother merging\n");
Matt Arsenault517d84e2013-10-01 18:05:30 +00001812 return false;
1813 }
1814 }
1815
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001816 // Impose a total order (by name) on the replacement of functions. This is
1817 // important when operating on more than one module independently to prevent
1818 // cycles of thunks calling each other when the modules are linked together.
1819 //
1820 // When one function is weak and the other is strong there is an order imposed
1821 // already. We process strong functions before weak functions.
1822 if ((OldF.getFunc()->mayBeOverridden() && NewFunction->mayBeOverridden()) ||
1823 (!OldF.getFunc()->mayBeOverridden() && !NewFunction->mayBeOverridden()))
1824 if (OldF.getFunc()->getName() > NewFunction->getName()) {
1825 // Swap the two functions.
1826 Function *F = OldF.getFunc();
JF Bastien3a4ad612015-09-02 23:55:23 +00001827 replaceFunctionInTree(*Result.first, NewFunction);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001828 NewFunction = F;
1829 assert(OldF.getFunc() != F && "Must have swapped the functions.");
1830 }
1831
Nick Lewycky00959372010-09-05 08:22:49 +00001832 // Never thunk a strong function to a weak function.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001833 assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
Nick Lewycky00959372010-09-05 08:22:49 +00001834
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001835 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
1836 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001837
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001838 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001839 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001840 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001841}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001842
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001843// Remove a function from FnTree. If it was already in FnTree, add
1844// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001845void MergeFunctions::remove(Function *F) {
JF Bastien3a4ad612015-09-02 23:55:23 +00001846 auto I = FNodesInTree.find(F);
1847 if (I != FNodesInTree.end()) {
1848 DEBUG(dbgs() << "Deferred " << F->getName()<< ".\n");
1849 FnTree.erase(I->second);
1850 // I->second has been invalidated, remove it from the FNodesInTree map to
1851 // preserve the invariant.
1852 FNodesInTree.erase(I);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001853 Deferred.emplace_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001854 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001855}
Nick Lewycky00959372010-09-05 08:22:49 +00001856
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001857// For each instruction used by the value, remove() the function that contains
1858// the instruction. This should happen right before a call to RAUW.
1859void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001860 std::vector<Value *> Worklist;
1861 Worklist.push_back(V);
JF Bastien7289f732015-07-15 21:51:33 +00001862 SmallSet<Value*, 8> Visited;
1863 Visited.insert(V);
Nick Lewycky5361b842011-01-02 19:16:44 +00001864 while (!Worklist.empty()) {
1865 Value *V = Worklist.back();
1866 Worklist.pop_back();
1867
Chandler Carruthcdf47882014-03-09 03:16:01 +00001868 for (User *U : V->users()) {
1869 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001870 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001871 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001872 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001873 } else if (Constant *C = dyn_cast<Constant>(U)) {
JF Bastien7289f732015-07-15 21:51:33 +00001874 for (User *UU : C->users()) {
1875 if (!Visited.insert(UU).second)
1876 Worklist.push_back(UU);
1877 }
Nick Lewycky5361b842011-01-02 19:16:44 +00001878 }
Nick Lewycky00959372010-09-05 08:22:49 +00001879 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001880 }
Nick Lewycky00959372010-09-05 08:22:49 +00001881}