blob: a31a08039796300ce075e17913c02e4c5e8b66b1 [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>
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000116using namespace llvm;
117
Chandler Carruth964daaa2014-04-22 02:55:47 +0000118#define DEBUG_TYPE "mergefunc"
119
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000120STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +0000121STATISTIC(NumThunksWritten, "Number of thunks generated");
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000122STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky71972d42010-09-07 01:42:10 +0000123STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000124
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000125static cl::opt<unsigned> NumFunctionsForSanityCheck(
126 "mergefunc-sanity",
127 cl::desc("How many functions in module could be used for "
128 "MergeFunctions pass sanity check. "
129 "'0' disables this check. Works only with '-debug' key."),
130 cl::init(0), cl::Hidden);
131
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000132namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000133
JF Bastien057292a2015-08-21 23:27:24 +0000134/// GlobalNumberState assigns an integer to each global value in the program,
135/// which is used by the comparison routine to order references to globals. This
136/// state must be preserved throughout the pass, because Functions and other
137/// globals need to maintain their relative order. Globals are assigned a number
138/// when they are first visited. This order is deterministic, and so the
139/// assigned numbers are as well. When two functions are merged, neither number
140/// is updated. If the symbols are weak, this would be incorrect. If they are
141/// strong, then one will be replaced at all references to the other, and so
142/// direct callsites will now see one or the other symbol, and no update is
143/// necessary. Note that if we were guaranteed unique names, we could just
144/// compare those, but this would not work for stripped bitcodes or for those
145/// few symbols without a name.
146class GlobalNumberState {
147 struct Config : ValueMapConfig<GlobalValue*> {
148 enum { FollowRAUW = false };
149 };
150 // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW
151 // occurs, the mapping does not change. Tracking changes is unnecessary, and
152 // also problematic for weak symbols (which may be overwritten).
153 typedef ValueMap<GlobalValue *, uint64_t, Config> ValueNumberMap;
154 ValueNumberMap GlobalNumbers;
155 // The next unused serial number to assign to a global.
156 uint64_t NextNumber;
157 public:
158 GlobalNumberState() : GlobalNumbers(), NextNumber(0) {}
159 uint64_t getNumber(GlobalValue* Global) {
160 ValueNumberMap::iterator MapIter;
161 bool Inserted;
162 std::tie(MapIter, Inserted) = GlobalNumbers.insert({Global, NextNumber});
163 if (Inserted)
164 NextNumber++;
165 return MapIter->second;
166 }
167};
168
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000169/// FunctionComparator - Compares two functions to determine whether or not
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000170/// they will generate machine code with the same behaviour. DataLayout is
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000171/// used if available. The comparator always fails conservatively (erring on the
172/// side of claiming that two functions are different).
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000173class FunctionComparator {
174public:
JF Bastien057292a2015-08-21 23:27:24 +0000175 FunctionComparator(const Function *F1, const Function *F2,
176 GlobalNumberState* GN)
177 : FnL(F1), FnR(F2), GlobalNumbers(GN) {}
Nick Lewyckye04dc222009-06-12 08:04:51 +0000178
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000179 /// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000180 int compare();
JF Bastien5e4303d2015-08-15 01:18:18 +0000181 /// Hash a function. Equivalent functions will have the same hash, and unequal
182 /// functions will have different hashes with high probability.
183 typedef uint64_t FunctionHash;
184 static FunctionHash functionHash(Function &);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000185
186private:
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000187 /// Test whether two basic blocks have equivalent behaviour.
JF Bastien057292a2015-08-21 23:27:24 +0000188 int cmpBasicBlocks(const BasicBlock *BBL, const BasicBlock *BBR);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000189
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000190 /// Constants comparison.
191 /// Its analog to lexicographical comparison between hypothetical numbers
192 /// of next format:
193 /// <bitcastability-trait><raw-bit-contents>
194 ///
195 /// 1. Bitcastability.
196 /// Check whether L's type could be losslessly bitcasted to R's type.
197 /// On this stage method, in case when lossless bitcast is not possible
198 /// method returns -1 or 1, thus also defining which type is greater in
199 /// context of bitcastability.
200 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
201 /// to the contents comparison.
202 /// If types differ, remember types comparison result and check
203 /// whether we still can bitcast types.
204 /// Stage 1: Types that satisfies isFirstClassType conditions are always
205 /// greater then others.
206 /// Stage 2: Vector is greater then non-vector.
207 /// If both types are vectors, then vector with greater bitwidth is
208 /// greater.
209 /// If both types are vectors with the same bitwidth, then types
210 /// are bitcastable, and we can skip other stages, and go to contents
211 /// comparison.
212 /// Stage 3: Pointer types are greater than non-pointers. If both types are
213 /// pointers of the same address space - go to contents comparison.
214 /// Different address spaces: pointer with greater address space is
215 /// greater.
216 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
217 /// We don't know how to bitcast them. So, we better don't do it,
218 /// and return types comparison result (so it determines the
219 /// relationship among constants we don't know how to bitcast).
220 ///
221 /// Just for clearance, let's see how the set of constants could look
222 /// on single dimension axis:
223 ///
224 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
225 /// Where: NFCT - Not a FirstClassType
226 /// FCT - FirstClassTyp:
227 ///
228 /// 2. Compare raw contents.
229 /// It ignores types on this stage and only compares bits from L and R.
230 /// Returns 0, if L and R has equivalent contents.
231 /// -1 or 1 if values are different.
232 /// Pretty trivial:
233 /// 2.1. If contents are numbers, compare numbers.
234 /// Ints with greater bitwidth are greater. Ints with same bitwidths
235 /// compared by their contents.
236 /// 2.2. "And so on". Just to avoid discrepancies with comments
237 /// perhaps it would be better to read the implementation itself.
238 /// 3. And again about overall picture. Let's look back at how the ordered set
239 /// of constants will look like:
240 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
241 ///
242 /// Now look, what could be inside [FCT, "others"], for example:
243 /// [FCT, "others"] =
244 /// [
245 /// [double 0.1], [double 1.23],
246 /// [i32 1], [i32 2],
247 /// { double 1.0 }, ; StructTyID, NumElements = 1
248 /// { i32 1 }, ; StructTyID, NumElements = 1
249 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
250 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
251 /// ]
252 ///
253 /// Let's explain the order. Float numbers will be less than integers, just
254 /// because of cmpType terms: FloatTyID < IntegerTyID.
255 /// Floats (with same fltSemantics) are sorted according to their value.
256 /// Then you can see integers, and they are, like a floats,
257 /// could be easy sorted among each others.
258 /// The structures. Structures are grouped at the tail, again because of their
259 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
260 /// Structures with greater number of elements are greater. Structures with
261 /// greater elements going first are greater.
262 /// The same logic with vectors, arrays and other possible complex types.
263 ///
264 /// Bitcastable constants.
265 /// Let's assume, that some constant, belongs to some group of
266 /// "so-called-equal" values with different types, and at the same time
267 /// belongs to another group of constants with equal types
268 /// and "really" equal values.
269 ///
270 /// Now, prove that this is impossible:
271 ///
272 /// If constant A with type TyA is bitcastable to B with type TyB, then:
273 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
274 /// those should be vectors (if TyA is vector), pointers
275 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
276 /// be equal to TyB.
277 /// 2. All constants with non-equal, but bitcastable types to TyA, are
278 /// bitcastable to B.
279 /// Once again, just because we allow it to vectors and pointers only.
280 /// This statement could be expanded as below:
281 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
282 /// vector B, and thus bitcastable to B as well.
283 /// 2.2. All pointers of the same address space, no matter what they point to,
284 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
285 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
286 /// QED.
287 ///
288 /// In another words, for pointers and vectors, we ignore top-level type and
289 /// look at their particular properties (bit-width for vectors, and
290 /// address space for pointers).
291 /// If these properties are equal - compare their contents.
292 int cmpConstants(const Constant *L, const Constant *R);
293
JF Bastien057292a2015-08-21 23:27:24 +0000294 /// Compares two global values by number. Uses the GlobalNumbersState to
295 /// identify the same gobals across function calls.
296 int cmpGlobalValues(GlobalValue *L, GlobalValue *R);
297
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000298 /// Assign or look up previously assigned numbers for the two values, and
299 /// return whether the numbers are equal. Numbers are assigned in the order
300 /// visited.
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000301 /// Comparison order:
302 /// Stage 0: Value that is function itself is always greater then others.
303 /// If left and right values are references to their functions, then
304 /// they are equal.
305 /// Stage 1: Constants are greater than non-constants.
306 /// If both left and right are constants, then the result of
307 /// cmpConstants is used as cmpValues result.
308 /// Stage 2: InlineAsm instances are greater than others. If both left and
309 /// right are InlineAsm instances, InlineAsm* pointers casted to
310 /// integers and compared as numbers.
311 /// Stage 3: For all other cases we compare order we meet these values in
312 /// their functions. If right value was met first during scanning,
313 /// then left value is greater.
314 /// In another words, we compare serial numbers, for more details
315 /// see comments for sn_mapL and sn_mapR.
316 int cmpValues(const Value *L, const Value *R);
317
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000318 /// Compare two Instructions for equivalence, similar to
319 /// Instruction::isSameOperationAs but with modifications to the type
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000320 /// comparison.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000321 /// Stages are listed in "most significant stage first" order:
322 /// On each stage below, we do comparison between some left and right
323 /// operation parts. If parts are non-equal, we assign parts comparison
324 /// result to the operation comparison result and exit from method.
325 /// Otherwise we proceed to the next stage.
326 /// Stages:
327 /// 1. Operations opcodes. Compared as numbers.
328 /// 2. Number of operands.
329 /// 3. Operation types. Compared with cmpType method.
330 /// 4. Compare operation subclass optional data as stream of bytes:
331 /// just convert it to integers and call cmpNumbers.
332 /// 5. Compare in operation operand types with cmpType in
333 /// most significant operand first order.
334 /// 6. Last stage. Check operations for some specific attributes.
335 /// For example, for Load it would be:
336 /// 6.1.Load: volatile (as boolean flag)
337 /// 6.2.Load: alignment (as integer numbers)
338 /// 6.3.Load: synch-scope (as integer numbers)
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000339 /// 6.4.Load: range metadata (as integer numbers)
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000340 /// On this stage its better to see the code, since its not more than 10-15
341 /// strings for particular instruction, and could change sometimes.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000342 int cmpOperations(const Instruction *L, const Instruction *R) const;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000343
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000344 /// Compare two GEPs for equivalent pointer arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000345 /// Parts to be compared for each comparison stage,
346 /// most significant stage first:
347 /// 1. Address space. As numbers.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000348 /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000349 /// 3. Pointer operand type (using cmpType method).
350 /// 4. Number of operands.
351 /// 5. Compare operands, using cmpValues method.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000352 int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR);
353 int cmpGEPs(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) {
354 return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000355 }
356
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000357 /// cmpType - compares two types,
358 /// defines total ordering among the types set.
359 ///
360 /// Return values:
361 /// 0 if types are equal,
362 /// -1 if Left is less than Right,
363 /// +1 if Left is greater than Right.
364 ///
365 /// Description:
366 /// Comparison is broken onto stages. Like in lexicographical comparison
367 /// stage coming first has higher priority.
368 /// On each explanation stage keep in mind total ordering properties.
369 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000370 /// 0. Before comparison we coerce pointer types of 0 address space to
371 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000372 /// We also don't bother with same type at left and right, so
373 /// just return 0 in this case.
374 ///
375 /// 1. If types are of different kind (different type IDs).
376 /// Return result of type IDs comparison, treating them as numbers.
JF Bastien057292a2015-08-21 23:27:24 +0000377 /// 2. If types are integers, check that they have the same width. If they
378 /// are vectors, check that they have the same count and subtype.
379 /// 3. Types have the same ID, so check whether they are one of:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000380 /// * Void
381 /// * Float
382 /// * Double
383 /// * X86_FP80
384 /// * FP128
385 /// * PPC_FP128
386 /// * Label
387 /// * Metadata
JF Bastien057292a2015-08-21 23:27:24 +0000388 /// We can treat these types as equal whenever their IDs are same.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000389 /// 4. If Left and Right are pointers, return result of address space
390 /// comparison (numbers comparison). We can treat pointer types of same
391 /// address space as equal.
392 /// 5. If types are complex.
393 /// Then both Left and Right are to be expanded and their element types will
394 /// be checked with the same way. If we get Res != 0 on some stage, return it.
395 /// Otherwise return 0.
396 /// 6. For all other cases put llvm_unreachable.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000397 int cmpTypes(Type *TyL, Type *TyR) const;
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000398
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000399 int cmpNumbers(uint64_t L, uint64_t R) const;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000400
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000401 int cmpAPInts(const APInt &L, const APInt &R) const;
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000402 int cmpAPFloats(const APFloat &L, const APFloat &R) const;
JF Bastien057292a2015-08-21 23:27:24 +0000403 int cmpInlineAsm(const InlineAsm *L, const InlineAsm *R) const;
404 int cmpMem(StringRef L, StringRef R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000405 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000406
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000407 // The two functions undergoing comparison.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000408 const Function *FnL, *FnR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000409
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000410 /// Assign serial numbers to values from left function, and values from
411 /// right function.
412 /// Explanation:
413 /// Being comparing functions we need to compare values we meet at left and
414 /// right sides.
415 /// Its easy to sort things out for external values. It just should be
416 /// the same value at left and right.
417 /// But for local values (those were introduced inside function body)
418 /// we have to ensure they were introduced at exactly the same place,
419 /// and plays the same role.
420 /// Let's assign serial number to each value when we meet it first time.
421 /// Values that were met at same place will be with same serial numbers.
422 /// In this case it would be good to explain few points about values assigned
423 /// to BBs and other ways of implementation (see below).
424 ///
425 /// 1. Safety of BB reordering.
426 /// It's safe to change the order of BasicBlocks in function.
427 /// Relationship with other functions and serial numbering will not be
428 /// changed in this case.
429 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
430 /// from the entry, and then take each terminator. So it doesn't matter how in
431 /// fact BBs are ordered in function. And since cmpValues are called during
432 /// this walk, the numbering depends only on how BBs located inside the CFG.
433 /// So the answer is - yes. We will get the same numbering.
434 ///
435 /// 2. Impossibility to use dominance properties of values.
436 /// If we compare two instruction operands: first is usage of local
437 /// variable AL from function FL, and second is usage of local variable AR
438 /// from FR, we could compare their origins and check whether they are
439 /// defined at the same place.
440 /// But, we are still not able to compare operands of PHI nodes, since those
441 /// could be operands from further BBs we didn't scan yet.
442 /// So it's impossible to use dominance properties in general.
443 DenseMap<const Value*, int> sn_mapL, sn_mapR;
JF Bastien057292a2015-08-21 23:27:24 +0000444
445 // The global state we will use
446 GlobalNumberState* GlobalNumbers;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000447};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000448
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000449class FunctionNode {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000450 mutable AssertingVH<Function> F;
JF Bastien5e4303d2015-08-15 01:18:18 +0000451 FunctionComparator::FunctionHash Hash;
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000452public:
JF Bastien5e4303d2015-08-15 01:18:18 +0000453 // Note the hash is recalculated potentially multiple times, but it is cheap.
JF Bastien057292a2015-08-21 23:27:24 +0000454 FunctionNode(Function *F)
455 : F(F), Hash(FunctionComparator::functionHash(*F)) {}
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000456 Function *getFunc() const { return F; }
JF Bastien057292a2015-08-21 23:27:24 +0000457 FunctionComparator::FunctionHash getHash() const { return Hash; }
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000458
459 /// Replace the reference to the function F by the function G, assuming their
460 /// implementations are equal.
461 void replaceBy(Function *G) const {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000462 F = G;
463 }
464
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000465 void release() { F = 0; }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000466};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000467}
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000468
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000469int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
470 if (L < R) return -1;
471 if (L > R) return 1;
472 return 0;
473}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000474
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000475int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000476 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
477 return Res;
478 if (L.ugt(R)) return 1;
479 if (R.ugt(L)) return -1;
480 return 0;
481}
482
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000483int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
JF Bastien057292a2015-08-21 23:27:24 +0000484 // TODO: This correctly handles all existing fltSemantics, because they all
485 // have different precisions. This isn't very robust, however, if new types
486 // with different exponent ranges are introduced.
487 const fltSemantics &SL = L.getSemantics(), &SR = R.getSemantics();
488 if (int Res = cmpNumbers(APFloat::semanticsPrecision(SL),
489 APFloat::semanticsPrecision(SR)))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000490 return Res;
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000491 return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000492}
493
JF Bastien057292a2015-08-21 23:27:24 +0000494int FunctionComparator::cmpMem(StringRef L, StringRef R) const {
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000495 // Prevent heavy comparison, compare sizes first.
496 if (int Res = cmpNumbers(L.size(), R.size()))
497 return Res;
498
499 // Compare strings lexicographically only when it is necessary: only when
500 // strings are equal in size.
501 return L.compare(R);
502}
503
504int FunctionComparator::cmpAttrs(const AttributeSet L,
505 const AttributeSet R) const {
506 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
507 return Res;
508
509 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
510 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
511 RE = R.end(i);
512 for (; LI != LE && RI != RE; ++LI, ++RI) {
513 Attribute LA = *LI;
514 Attribute RA = *RI;
515 if (LA < RA)
516 return -1;
517 if (RA < LA)
518 return 1;
519 }
520 if (LI != LE)
521 return 1;
522 if (RI != RE)
523 return -1;
524 }
525 return 0;
526}
527
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000528/// Constants comparison:
529/// 1. Check whether type of L constant could be losslessly bitcasted to R
530/// type.
531/// 2. Compare constant contents.
532/// For more details see declaration comments.
533int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) {
534
535 Type *TyL = L->getType();
536 Type *TyR = R->getType();
537
538 // Check whether types are bitcastable. This part is just re-factored
539 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
540 // we also pack into result which type is "less" for us.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000541 int TypesRes = cmpTypes(TyL, TyR);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000542 if (TypesRes != 0) {
543 // Types are different, but check whether we can bitcast them.
544 if (!TyL->isFirstClassType()) {
545 if (TyR->isFirstClassType())
546 return -1;
547 // Neither TyL nor TyR are values of first class type. Return the result
548 // of comparing the types
549 return TypesRes;
550 }
551 if (!TyR->isFirstClassType()) {
552 if (TyL->isFirstClassType())
553 return 1;
554 return TypesRes;
555 }
556
557 // Vector -> Vector conversions are always lossless if the two vector types
558 // have the same size, otherwise not.
559 unsigned TyLWidth = 0;
560 unsigned TyRWidth = 0;
561
Craig Toppere3dcce92015-08-01 22:20:21 +0000562 if (auto *VecTyL = dyn_cast<VectorType>(TyL))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000563 TyLWidth = VecTyL->getBitWidth();
Craig Toppere3dcce92015-08-01 22:20:21 +0000564 if (auto *VecTyR = dyn_cast<VectorType>(TyR))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000565 TyRWidth = VecTyR->getBitWidth();
566
567 if (TyLWidth != TyRWidth)
568 return cmpNumbers(TyLWidth, TyRWidth);
569
570 // Zero bit-width means neither TyL nor TyR are vectors.
571 if (!TyLWidth) {
572 PointerType *PTyL = dyn_cast<PointerType>(TyL);
573 PointerType *PTyR = dyn_cast<PointerType>(TyR);
574 if (PTyL && PTyR) {
575 unsigned AddrSpaceL = PTyL->getAddressSpace();
576 unsigned AddrSpaceR = PTyR->getAddressSpace();
577 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
578 return Res;
579 }
580 if (PTyL)
581 return 1;
582 if (PTyR)
583 return -1;
584
585 // TyL and TyR aren't vectors, nor pointers. We don't know how to
586 // bitcast them.
587 return TypesRes;
588 }
589 }
590
591 // OK, types are bitcastable, now check constant contents.
592
593 if (L->isNullValue() && R->isNullValue())
594 return TypesRes;
595 if (L->isNullValue() && !R->isNullValue())
596 return 1;
597 if (!L->isNullValue() && R->isNullValue())
598 return -1;
599
JF Bastien057292a2015-08-21 23:27:24 +0000600 auto GlobalValueL = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(L));
601 auto GlobalValueR = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(R));
602 if (GlobalValueL && GlobalValueR) {
603 return cmpGlobalValues(GlobalValueL, GlobalValueR);
604 }
605
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000606 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
607 return Res;
608
JF Bastien057292a2015-08-21 23:27:24 +0000609 if (const auto *SeqL = dyn_cast<ConstantDataSequential>(L)) {
610 const auto *SeqR = dyn_cast<ConstantDataSequential>(R);
611 // This handles ConstantDataArray and ConstantDataVector. Note that we
612 // compare the two raw data arrays, which might differ depending on the host
613 // endianness. This isn't a problem though, because the endiness of a module
614 // will affect the order of the constants, but this order is the same
615 // for a given input module and host platform.
616 return cmpMem(SeqL->getRawDataValues(), SeqR->getRawDataValues());
617 }
618
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000619 switch (L->getValueID()) {
620 case Value::UndefValueVal: return TypesRes;
621 case Value::ConstantIntVal: {
622 const APInt &LInt = cast<ConstantInt>(L)->getValue();
623 const APInt &RInt = cast<ConstantInt>(R)->getValue();
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000624 return cmpAPInts(LInt, RInt);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000625 }
626 case Value::ConstantFPVal: {
627 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
628 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000629 return cmpAPFloats(LAPF, RAPF);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000630 }
631 case Value::ConstantArrayVal: {
632 const ConstantArray *LA = cast<ConstantArray>(L);
633 const ConstantArray *RA = cast<ConstantArray>(R);
634 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
635 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
636 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
637 return Res;
638 for (uint64_t i = 0; i < NumElementsL; ++i) {
639 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
640 cast<Constant>(RA->getOperand(i))))
641 return Res;
642 }
643 return 0;
644 }
645 case Value::ConstantStructVal: {
646 const ConstantStruct *LS = cast<ConstantStruct>(L);
647 const ConstantStruct *RS = cast<ConstantStruct>(R);
648 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
649 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
650 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
651 return Res;
652 for (unsigned i = 0; i != NumElementsL; ++i) {
653 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
654 cast<Constant>(RS->getOperand(i))))
655 return Res;
656 }
657 return 0;
658 }
659 case Value::ConstantVectorVal: {
660 const ConstantVector *LV = cast<ConstantVector>(L);
661 const ConstantVector *RV = cast<ConstantVector>(R);
662 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
663 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
664 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
665 return Res;
666 for (uint64_t i = 0; i < NumElementsL; ++i) {
667 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
668 cast<Constant>(RV->getOperand(i))))
669 return Res;
670 }
671 return 0;
672 }
673 case Value::ConstantExprVal: {
674 const ConstantExpr *LE = cast<ConstantExpr>(L);
675 const ConstantExpr *RE = cast<ConstantExpr>(R);
676 unsigned NumOperandsL = LE->getNumOperands();
677 unsigned NumOperandsR = RE->getNumOperands();
678 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
679 return Res;
680 for (unsigned i = 0; i < NumOperandsL; ++i) {
681 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
682 cast<Constant>(RE->getOperand(i))))
683 return Res;
684 }
685 return 0;
686 }
JF Bastien057292a2015-08-21 23:27:24 +0000687 case Value::BlockAddressVal: {
688 // FIXME: This still uses a pointer comparison. It isn't clear how to remove
689 // this. This only affects programs which take BlockAddresses and store them
690 // as constants, which is limited to interepreters, etc.
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000691 return cmpNumbers((uint64_t)L, (uint64_t)R);
692 }
JF Bastien057292a2015-08-21 23:27:24 +0000693 default: // Unknown constant, abort.
694 DEBUG(dbgs() << "Looking at valueID " << L->getValueID() << "\n");
695 llvm_unreachable("Constant ValueID not recognized.");
696 return -1;
697 }
698}
699
700int FunctionComparator::cmpGlobalValues(GlobalValue *L, GlobalValue* R) {
701 return cmpNumbers(GlobalNumbers->getNumber(L), GlobalNumbers->getNumber(R));
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000702}
703
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000704/// cmpType - compares two types,
705/// defines total ordering among the types set.
706/// See method declaration comments for more details.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000707int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000708
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000709 PointerType *PTyL = dyn_cast<PointerType>(TyL);
710 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000711
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000712 const DataLayout &DL = FnL->getParent()->getDataLayout();
713 if (PTyL && PTyL->getAddressSpace() == 0)
714 TyL = DL.getIntPtrType(TyL);
715 if (PTyR && PTyR->getAddressSpace() == 0)
716 TyR = DL.getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000717
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000718 if (TyL == TyR)
719 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000720
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000721 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
722 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000723
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000724 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000725 default:
726 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000727 // Fall through in Release mode.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000728 case Type::IntegerTyID:
JF Bastien057292a2015-08-21 23:27:24 +0000729 return cmpNumbers(cast<IntegerType>(TyL)->getBitWidth(),
730 cast<IntegerType>(TyR)->getBitWidth());
731 case Type::VectorTyID: {
732 VectorType *VTyL = cast<VectorType>(TyL), *VTyR = cast<VectorType>(TyR);
733 if (int Res = cmpNumbers(VTyL->getNumElements(), VTyR->getNumElements()))
734 return Res;
735 return cmpTypes(VTyL->getElementType(), VTyR->getElementType());
736 }
737 // TyL == TyR would have returned true earlier, because types are uniqued.
Nick Lewyckye04dc222009-06-12 08:04:51 +0000738 case Type::VoidTyID:
739 case Type::FloatTyID:
740 case Type::DoubleTyID:
741 case Type::X86_FP80TyID:
742 case Type::FP128TyID:
743 case Type::PPC_FP128TyID:
744 case Type::LabelTyID:
745 case Type::MetadataTyID:
David Majnemerb611e3f2015-08-14 05:09:07 +0000746 case Type::TokenTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000747 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000748
Nick Lewyckye04dc222009-06-12 08:04:51 +0000749 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000750 assert(PTyL && PTyR && "Both types must be pointers here.");
751 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000752 }
753
754 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000755 StructType *STyL = cast<StructType>(TyL);
756 StructType *STyR = cast<StructType>(TyR);
757 if (STyL->getNumElements() != STyR->getNumElements())
758 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000759
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000760 if (STyL->isPacked() != STyR->isPacked())
761 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000762
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000763 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000764 if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000765 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000766 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000767 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000768 }
769
770 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000771 FunctionType *FTyL = cast<FunctionType>(TyL);
772 FunctionType *FTyR = cast<FunctionType>(TyR);
773 if (FTyL->getNumParams() != FTyR->getNumParams())
774 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000775
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000776 if (FTyL->isVarArg() != FTyR->isVarArg())
777 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000778
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000779 if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000780 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000781
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000782 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000783 if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000784 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000785 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000786 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000787 }
788
Nick Lewycky375efe32010-07-16 06:31:12 +0000789 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000790 ArrayType *ATyL = cast<ArrayType>(TyL);
791 ArrayType *ATyR = cast<ArrayType>(TyR);
792 if (ATyL->getNumElements() != ATyR->getNumElements())
793 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000794 return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000795 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000796 }
797}
798
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000799// Determine whether the two operations are the same except that pointer-to-A
800// and pointer-to-B are equivalent. This should be kept in sync with
801// Instruction::isSameOperationAs.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000802// Read method declaration comments for more details.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000803int FunctionComparator::cmpOperations(const Instruction *L,
804 const Instruction *R) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000805 // Differences from Instruction::isSameOperationAs:
806 // * replace type comparison with calls to isEquivalentType.
807 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top
808 // * because of the above, we don't test for the tail bit on calls later on
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000809 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
810 return Res;
811
812 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
813 return Res;
814
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000815 if (int Res = cmpTypes(L->getType(), R->getType()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000816 return Res;
817
818 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
819 R->getRawSubclassOptionalData()))
820 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000821
Arnold Schwaighofer6a8c5f62015-05-12 21:42:22 +0000822 if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
823 if (int Res = cmpTypes(AI->getAllocatedType(),
824 cast<AllocaInst>(R)->getAllocatedType()))
825 return Res;
826 if (int Res =
827 cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment()))
828 return Res;
829 }
830
Nick Lewyckye04dc222009-06-12 08:04:51 +0000831 // We have two instructions of identical opcode and #operands. Check to see
832 // if all operands are the same type
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000833 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
834 if (int Res =
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000835 cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000836 return Res;
837 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000838
839 // Check special state that is a part of some instructions.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000840 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
841 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
842 return Res;
843 if (int Res =
844 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
845 return Res;
846 if (int Res =
847 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
848 return Res;
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000849 if (int Res =
850 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
851 return Res;
852 return cmpNumbers((uint64_t)LI->getMetadata(LLVMContext::MD_range),
853 (uint64_t)cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000854 }
855 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
856 if (int Res =
857 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
858 return Res;
859 if (int Res =
860 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
861 return Res;
862 if (int Res =
863 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
864 return Res;
865 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
866 }
867 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
868 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
869 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
870 if (int Res = cmpNumbers(CI->getCallingConv(),
871 cast<CallInst>(R)->getCallingConv()))
872 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000873 if (int Res =
874 cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
875 return Res;
876 return cmpNumbers(
877 (uint64_t)CI->getMetadata(LLVMContext::MD_range),
878 (uint64_t)cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000879 }
880 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) {
881 if (int Res = cmpNumbers(CI->getCallingConv(),
882 cast<InvokeInst>(R)->getCallingConv()))
883 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000884 if (int Res =
885 cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
886 return Res;
887 return cmpNumbers(
888 (uint64_t)CI->getMetadata(LLVMContext::MD_range),
889 (uint64_t)cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000890 }
891 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
892 ArrayRef<unsigned> LIndices = IVI->getIndices();
893 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
894 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
895 return Res;
896 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
897 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
898 return Res;
899 }
900 }
901 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
902 ArrayRef<unsigned> LIndices = EVI->getIndices();
903 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
904 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
905 return Res;
906 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
907 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
908 return Res;
909 }
910 }
911 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
912 if (int Res =
913 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
914 return Res;
915 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
916 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000917
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000918 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
919 if (int Res = cmpNumbers(CXI->isVolatile(),
920 cast<AtomicCmpXchgInst>(R)->isVolatile()))
921 return Res;
Tim Northover420a2162014-06-13 14:24:07 +0000922 if (int Res = cmpNumbers(CXI->isWeak(),
923 cast<AtomicCmpXchgInst>(R)->isWeak()))
924 return Res;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000925 if (int Res = cmpNumbers(CXI->getSuccessOrdering(),
926 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
927 return Res;
928 if (int Res = cmpNumbers(CXI->getFailureOrdering(),
929 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
930 return Res;
931 return cmpNumbers(CXI->getSynchScope(),
932 cast<AtomicCmpXchgInst>(R)->getSynchScope());
933 }
934 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
935 if (int Res = cmpNumbers(RMWI->getOperation(),
936 cast<AtomicRMWInst>(R)->getOperation()))
937 return Res;
938 if (int Res = cmpNumbers(RMWI->isVolatile(),
939 cast<AtomicRMWInst>(R)->isVolatile()))
940 return Res;
941 if (int Res = cmpNumbers(RMWI->getOrdering(),
942 cast<AtomicRMWInst>(R)->getOrdering()))
943 return Res;
944 return cmpNumbers(RMWI->getSynchScope(),
945 cast<AtomicRMWInst>(R)->getSynchScope());
946 }
947 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000948}
949
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000950// Determine whether two GEP operations perform the same underlying arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000951// Read method declaration comments for more details.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000952int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000953 const GEPOperator *GEPR) {
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000954
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000955 unsigned int ASL = GEPL->getPointerAddressSpace();
956 unsigned int ASR = GEPR->getPointerAddressSpace();
957
958 if (int Res = cmpNumbers(ASL, ASR))
959 return Res;
960
961 // When we have target data, we can reduce the GEP down to the value in bytes
962 // added to the address.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000963 const DataLayout &DL = FnL->getParent()->getDataLayout();
964 unsigned BitWidth = DL.getPointerSizeInBits(ASL);
965 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
966 if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
967 GEPR->accumulateConstantOffset(DL, OffsetR))
968 return cmpAPInts(OffsetL, OffsetR);
JF Bastien057292a2015-08-21 23:27:24 +0000969 if (int Res = cmpTypes(GEPL->getPointerOperand()->getType(),
970 GEPR->getPointerOperand()->getType()))
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000971 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000972
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000973 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
974 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000975
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000976 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
977 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
978 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000979 }
980
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000981 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000982}
983
JF Bastien057292a2015-08-21 23:27:24 +0000984int FunctionComparator::cmpInlineAsm(const InlineAsm *L,
985 const InlineAsm *R) const {
986 // InlineAsm's are uniqued. If they are the same pointer, obviously they are
987 // the same, otherwise compare the fields.
988 if (L == R)
989 return 0;
990 if (int Res = cmpTypes(L->getFunctionType(), R->getFunctionType()))
991 return Res;
992 if (int Res = cmpMem(L->getAsmString(), R->getAsmString()))
993 return Res;
994 if (int Res = cmpMem(L->getConstraintString(), R->getConstraintString()))
995 return Res;
996 if (int Res = cmpNumbers(L->hasSideEffects(), R->hasSideEffects()))
997 return Res;
998 if (int Res = cmpNumbers(L->isAlignStack(), R->isAlignStack()))
999 return Res;
1000 if (int Res = cmpNumbers(L->getDialect(), R->getDialect()))
1001 return Res;
1002 llvm_unreachable("InlineAsm blocks were not uniqued.");
1003 return 0;
1004}
1005
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001006/// Compare two values used by the two functions under pair-wise comparison. If
1007/// this is the first time the values are seen, they're added to the mapping so
1008/// that we will detect mismatches on next use.
1009/// See comments in declaration for more details.
1010int FunctionComparator::cmpValues(const Value *L, const Value *R) {
1011 // Catch self-reference case.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001012 if (L == FnL) {
1013 if (R == FnR)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001014 return 0;
1015 return -1;
1016 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001017 if (R == FnR) {
1018 if (L == FnL)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001019 return 0;
1020 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +00001021 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001022
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001023 const Constant *ConstL = dyn_cast<Constant>(L);
1024 const Constant *ConstR = dyn_cast<Constant>(R);
1025 if (ConstL && ConstR) {
1026 if (L == R)
1027 return 0;
1028 return cmpConstants(ConstL, ConstR);
1029 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001030
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001031 if (ConstL)
1032 return 1;
1033 if (ConstR)
1034 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001035
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001036 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
1037 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
1038
1039 if (InlineAsmL && InlineAsmR)
JF Bastien057292a2015-08-21 23:27:24 +00001040 return cmpInlineAsm(InlineAsmL, InlineAsmR);
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001041 if (InlineAsmL)
1042 return 1;
1043 if (InlineAsmR)
1044 return -1;
1045
1046 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
1047 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
1048
1049 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001050}
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001051// Test whether two basic blocks have equivalent behaviour.
JF Bastien057292a2015-08-21 23:27:24 +00001052int FunctionComparator::cmpBasicBlocks(const BasicBlock *BBL,
1053 const BasicBlock *BBR) {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001054 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
1055 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001056
1057 do {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001058 if (int Res = cmpValues(InstL, InstR))
1059 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001060
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001061 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
1062 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
Nick Lewycky47b71c52009-06-13 19:09:52 +00001063
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001064 if (GEPL && !GEPR)
1065 return 1;
1066 if (GEPR && !GEPL)
1067 return -1;
Nick Lewycky47b71c52009-06-13 19:09:52 +00001068
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001069 if (GEPL && GEPR) {
1070 if (int Res =
1071 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
1072 return Res;
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +00001073 if (int Res = cmpGEPs(GEPL, GEPR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001074 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001075 } else {
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +00001076 if (int Res = cmpOperations(InstL, InstR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001077 return Res;
1078 assert(InstL->getNumOperands() == InstR->getNumOperands());
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001079
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001080 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
1081 Value *OpL = InstL->getOperand(i);
1082 Value *OpR = InstR->getOperand(i);
1083 if (int Res = cmpValues(OpL, OpR))
1084 return Res;
1085 if (int Res = cmpNumbers(OpL->getValueID(), OpR->getValueID()))
1086 return Res;
1087 // TODO: Already checked in cmpOperation
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +00001088 if (int Res = cmpTypes(OpL->getType(), OpR->getType()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001089 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001090 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001091 }
1092
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001093 ++InstL, ++InstR;
1094 } while (InstL != InstLE && InstR != InstRE);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001095
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001096 if (InstL != InstLE && InstR == InstRE)
1097 return 1;
1098 if (InstL == InstLE && InstR != InstRE)
1099 return -1;
1100 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001101}
1102
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001103// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001104int FunctionComparator::compare() {
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001105
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001106 sn_mapL.clear();
1107 sn_mapR.clear();
1108
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001109 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1110 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001111
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001112 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1113 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001114
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001115 if (FnL->hasGC()) {
JF Bastien057292a2015-08-21 23:27:24 +00001116 if (int Res = cmpMem(FnL->getGC(), FnR->getGC()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001117 return Res;
1118 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001119
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001120 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1121 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001122
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001123 if (FnL->hasSection()) {
JF Bastien057292a2015-08-21 23:27:24 +00001124 if (int Res = cmpMem(FnL->getSection(), FnR->getSection()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001125 return Res;
1126 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001127
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001128 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1129 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001130
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001131 // TODO: if it's internal and only used in direct calls, we could handle this
1132 // case too.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001133 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1134 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001135
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +00001136 if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001137 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001138
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001139 assert(FnL->arg_size() == FnR->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +00001140 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001141
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001142 // Visit the arguments so that they get enumerated in the order they're
1143 // passed in.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001144 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1145 ArgRI = FnR->arg_begin(),
1146 ArgLE = FnL->arg_end();
1147 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
1148 if (cmpValues(ArgLI, ArgRI) != 0)
Nick Lewycky71972d42010-09-07 01:42:10 +00001149 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001150 }
1151
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001152 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1153 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001154 // functions, then takes each block from each terminator in order. As an
1155 // artifact, this also means that unreachable blocks are ignored.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001156 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001157 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001158
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001159 FnLBBs.push_back(&FnL->getEntryBlock());
1160 FnRBBs.push_back(&FnR->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001161
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001162 VisitedBBs.insert(FnLBBs[0]);
1163 while (!FnLBBs.empty()) {
1164 const BasicBlock *BBL = FnLBBs.pop_back_val();
1165 const BasicBlock *BBR = FnRBBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001166
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001167 if (int Res = cmpValues(BBL, BBR))
1168 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001169
JF Bastien057292a2015-08-21 23:27:24 +00001170 if (int Res = cmpBasicBlocks(BBL, BBR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001171 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001172
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001173 const TerminatorInst *TermL = BBL->getTerminator();
1174 const TerminatorInst *TermR = BBR->getTerminator();
1175
1176 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1177 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
David Blaikie70573dc2014-11-19 07:49:26 +00001178 if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
Nick Lewycky2b3cbac2010-05-13 06:45:13 +00001179 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001180
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001181 FnLBBs.push_back(TermL->getSuccessor(i));
1182 FnRBBs.push_back(TermR->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001183 }
1184 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001185 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001186}
1187
JF Bastien5e4303d2015-08-15 01:18:18 +00001188// Accumulate the hash of a sequence of 64-bit integers. This is similar to a
1189// hash of a sequence of 64bit ints, but the entire input does not need to be
1190// available at once. This interface is necessary for functionHash because it
1191// needs to accumulate the hash as the structure of the function is traversed
1192// without saving these values to an intermediate buffer. This form of hashing
1193// is not often needed, as usually the object to hash is just read from a
1194// buffer.
1195class HashAccumulator64 {
1196 uint64_t Hash;
1197public:
1198 // Initialize to random constant, so the state isn't zero.
1199 HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
1200 void add(uint64_t V) {
1201 Hash = llvm::hashing::detail::hash_16_bytes(Hash, V);
1202 }
1203 // No finishing is required, because the entire hash value is used.
1204 uint64_t getHash() { return Hash; }
1205};
1206
1207// A function hash is calculated by considering only the number of arguments and
1208// whether a function is varargs, the order of basic blocks (given by the
1209// successors of each basic block in depth first order), and the order of
1210// opcodes of each instruction within each of these basic blocks. This mirrors
1211// the strategy compare() uses to compare functions by walking the BBs in depth
1212// first order and comparing each instruction in sequence. Because this hash
1213// does not look at the operands, it is insensitive to things such as the
1214// target of calls and the constants used in the function, which makes it useful
1215// when possibly merging functions which are the same modulo constants and call
1216// targets.
1217FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
1218 HashAccumulator64 H;
1219 H.add(F.isVarArg());
1220 H.add(F.arg_size());
1221
1222 SmallVector<const BasicBlock *, 8> BBs;
1223 SmallSet<const BasicBlock *, 16> VisitedBBs;
1224
JF Bastien057292a2015-08-21 23:27:24 +00001225 // Walk the blocks in the same order as FunctionComparator::cmpBasicBlocks(),
JF Bastien5e4303d2015-08-15 01:18:18 +00001226 // accumulating the hash of the function "structure." (BB and opcode sequence)
1227 BBs.push_back(&F.getEntryBlock());
1228 VisitedBBs.insert(BBs[0]);
1229 while (!BBs.empty()) {
1230 const BasicBlock *BB = BBs.pop_back_val();
1231 // This random value acts as a block header, as otherwise the partition of
1232 // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
1233 H.add(45798);
1234 for (auto &Inst : *BB) {
1235 H.add(Inst.getOpcode());
1236 }
1237 const TerminatorInst *Term = BB->getTerminator();
1238 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
1239 if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
1240 continue;
1241 BBs.push_back(Term->getSuccessor(i));
1242 }
1243 }
1244 return H.getHash();
1245}
1246
1247
Nick Lewycky564fcca2011-01-28 07:36:21 +00001248namespace {
1249
1250/// MergeFunctions finds functions which will generate identical machine code,
1251/// by considering all pointer types to be equivalent. Once identified,
1252/// MergeFunctions will fold them by replacing a call to one to a call to a
1253/// bitcast of the other.
1254///
1255class MergeFunctions : public ModulePass {
1256public:
1257 static char ID;
1258 MergeFunctions()
JF Bastien057292a2015-08-21 23:27:24 +00001259 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)),
1260 HasGlobalAliases(false) {
Nick Lewycky564fcca2011-01-28 07:36:21 +00001261 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1262 }
1263
Craig Topper3e4c6972014-03-05 09:10:37 +00001264 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001265
1266private:
JF Bastien057292a2015-08-21 23:27:24 +00001267 // The function comparison operator is provided here so that FunctionNodes do
1268 // not need to become larger with another pointer.
1269 class FunctionNodeCmp {
1270 GlobalNumberState* GlobalNumbers;
1271 public:
1272 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
1273 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
1274 // Order first by hashes, then full function comparison.
1275 if (LHS.getHash() != RHS.getHash())
1276 return LHS.getHash() < RHS.getHash();
1277 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
1278 return FCmp.compare() == -1;
1279 }
1280 };
1281 typedef std::set<FunctionNode, FunctionNodeCmp> FnTreeType;
1282
1283 GlobalNumberState GlobalNumbers;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001284
1285 /// A work queue of functions that may have been modified and should be
1286 /// analyzed again.
1287 std::vector<WeakVH> Deferred;
1288
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001289 /// Checks the rules of order relation introduced among functions set.
1290 /// Returns true, if sanity check has been passed, and false if failed.
1291 bool doSanityCheck(std::vector<WeakVH> &Worklist);
1292
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001293 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +00001294 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001295 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001296
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001297 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +00001298 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001299 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001300
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001301 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +00001302 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001303 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001304
1305 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1306 /// necessary to make types match.
1307 void replaceDirectCallers(Function *Old, Function *New);
1308
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001309 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1310 /// be converted into a thunk. In either case, it should never be visited
1311 /// again.
1312 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001313
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001314 /// Replace G with a thunk or an alias to F. Deletes G.
1315 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001316
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001317 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1318 /// of G with bitcast(F). Deletes G.
1319 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001320
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001321 /// Replace G with an alias to F. Deletes G.
1322 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001323
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001324 /// Replace function F with function G in the function tree.
1325 void replaceFunctionInTree(FnTreeType::iterator &IterToF, Function *G);
1326
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001327 /// The set of all distinct functions. Use the insert() and remove() methods
1328 /// to modify it.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001329 FnTreeType FnTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001330
Nick Lewycky564fcca2011-01-28 07:36:21 +00001331 /// Whether or not the target supports global aliases.
1332 bool HasGlobalAliases;
1333};
1334
1335} // end anonymous namespace
1336
1337char MergeFunctions::ID = 0;
1338INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1339
1340ModulePass *llvm::createMergeFunctionsPass() {
1341 return new MergeFunctions();
1342}
1343
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001344bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1345 if (const unsigned Max = NumFunctionsForSanityCheck) {
1346 unsigned TripleNumber = 0;
1347 bool Valid = true;
1348
1349 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1350
1351 unsigned i = 0;
1352 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1353 I != E && i < Max; ++I, ++i) {
1354 unsigned j = i;
1355 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1356 Function *F1 = cast<Function>(*I);
1357 Function *F2 = cast<Function>(*J);
JF Bastien057292a2015-08-21 23:27:24 +00001358 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
1359 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001360
1361 // If F1 <= F2, then F2 >= F1, otherwise report failure.
1362 if (Res1 != -Res2) {
1363 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1364 << "\n";
1365 F1->dump();
1366 F2->dump();
1367 Valid = false;
1368 }
1369
1370 if (Res1 == 0)
1371 continue;
1372
1373 unsigned k = j;
1374 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1375 ++k, ++K, ++TripleNumber) {
1376 if (K == J)
1377 continue;
1378
1379 Function *F3 = cast<Function>(*K);
JF Bastien057292a2015-08-21 23:27:24 +00001380 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
1381 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001382
1383 bool Transitive = true;
1384
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001385 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001386 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001387 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001388 } else if (Res3 != 0 && Res3 == -Res4) {
1389 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001390 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001391 } else if (Res4 != 0 && -Res3 == Res4) {
1392 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001393 Transitive = Res4 == -Res1;
1394 }
1395
1396 if (!Transitive) {
1397 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1398 << TripleNumber << "\n";
1399 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1400 << Res4 << "\n";
1401 F1->dump();
1402 F2->dump();
1403 F3->dump();
1404 Valid = false;
1405 }
1406 }
1407 }
1408 }
1409
1410 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1411 return Valid;
1412 }
1413 return true;
1414}
1415
Nick Lewycky564fcca2011-01-28 07:36:21 +00001416bool MergeFunctions::runOnModule(Module &M) {
1417 bool Changed = false;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001418
JF Bastien5e4303d2015-08-15 01:18:18 +00001419 // All functions in the module, ordered by hash. Functions with a unique
1420 // hash value are easily eliminated.
1421 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
1422 HashedFuncs;
1423 for (Function &Func : M) {
1424 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
1425 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
1426 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001427 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001428
NAKAMURA Takumi51962752015-08-16 02:41:23 +00001429 std::stable_sort(
1430 HashedFuncs.begin(), HashedFuncs.end(),
1431 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
1432 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
1433 return a.first < b.first;
1434 });
JF Bastien5e4303d2015-08-15 01:18:18 +00001435
1436 auto S = HashedFuncs.begin();
1437 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
1438 // If the hash value matches the previous value or the next one, we must
1439 // consider merging it. Otherwise it is dropped and never considered again.
1440 if ((I != S && std::prev(I)->first == I->first) ||
1441 (std::next(I) != IE && std::next(I)->first == I->first) ) {
1442 Deferred.push_back(WeakVH(I->second));
1443 }
1444 }
1445
Nick Lewycky564fcca2011-01-28 07:36:21 +00001446 do {
1447 std::vector<WeakVH> Worklist;
1448 Deferred.swap(Worklist);
1449
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001450 DEBUG(doSanityCheck(Worklist));
1451
Nick Lewycky564fcca2011-01-28 07:36:21 +00001452 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1453 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1454
1455 // Insert only strong functions and merge them. Strong function merging
1456 // always deletes one of them.
1457 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1458 E = Worklist.end(); I != E; ++I) {
1459 if (!*I) continue;
1460 Function *F = cast<Function>(*I);
1461 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1462 !F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001463 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001464 }
1465 }
1466
1467 // Insert only weak functions and merge them. By doing these second we
1468 // create thunks to the strong function when possible. When two weak
1469 // functions are identical, we create a new strong function with two weak
1470 // weak thunks to it which are identical but not mergable.
1471 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
1472 E = Worklist.end(); I != E; ++I) {
1473 if (!*I) continue;
1474 Function *F = cast<Function>(*I);
1475 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
1476 F->mayBeOverridden()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001477 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001478 }
1479 }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001480 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +00001481 } while (!Deferred.empty());
1482
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001483 FnTree.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +00001484
1485 return Changed;
1486}
1487
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001488// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001489void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1490 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001491 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1492 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001493 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001494 CallSite CS(U->getUser());
1495 if (CS && CS.isCallee(U)) {
Arnold Schwaighofer36512332015-07-21 17:07:07 +00001496 // Transfer the called function's attributes to the call site. Due to the
1497 // bitcast we will 'loose' ABI changing attributes because the 'called
1498 // function' is no longer a Function* but the bitcast. Code that looks up
1499 // the attributes from the called function will fail.
1500 auto &Context = New->getContext();
1501 auto NewFuncAttrs = New->getAttributes();
1502 auto CallSiteAttrs = CS.getAttributes();
1503
1504 CallSiteAttrs = CallSiteAttrs.addAttributes(
1505 Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes());
1506
1507 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) {
1508 AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx);
1509 if (Attrs.getNumSlots())
1510 CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs);
1511 }
1512
1513 CS.setAttributes(CallSiteAttrs);
1514
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001515 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001516 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001517 }
1518 }
1519}
1520
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001521// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1522void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001523 if (HasGlobalAliases && G->hasUnnamedAddr()) {
1524 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1525 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001526 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001527 return;
1528 }
1529 }
1530
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001531 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001532}
1533
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001534// Helper for writeThunk,
1535// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001536// but a bit simpler then CastInst::getCastOpcode.
Carlo Kok307625c2014-04-30 17:53:04 +00001537static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001538 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001539 if (SrcTy->isStructTy()) {
1540 assert(DestTy->isStructTy());
1541 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1542 Value *Result = UndefValue::get(DestTy);
1543 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1544 Value *Element = createCast(
Craig Toppere1d12942014-08-27 05:25:25 +00001545 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
Carlo Kok307625c2014-04-30 17:53:04 +00001546 DestTy->getStructElementType(I));
1547
1548 Result =
Craig Toppere1d12942014-08-27 05:25:25 +00001549 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
Carlo Kok307625c2014-04-30 17:53:04 +00001550 }
1551 return Result;
1552 }
1553 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001554 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1555 return Builder.CreateIntToPtr(V, DestTy);
1556 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1557 return Builder.CreatePtrToInt(V, DestTy);
1558 else
1559 return Builder.CreateBitCast(V, DestTy);
1560}
1561
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001562// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1563// of G with bitcast(F). Deletes G.
1564void MergeFunctions::writeThunk(Function *F, Function *G) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001565 if (!G->mayBeOverridden()) {
1566 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001567 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001568 }
1569
Nick Lewycky71972d42010-09-07 01:42:10 +00001570 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001571 // stop here and delete G. There's no need for a thunk.
1572 if (G->hasLocalLinkage() && G->use_empty()) {
1573 G->eraseFromParent();
1574 return;
1575 }
1576
Nick Lewycky25675ac2009-06-12 15:56:56 +00001577 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1578 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001579 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001580 IRBuilder<false> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001581
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001582 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001583 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001584 FunctionType *FFTy = F->getFunctionType();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001585 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end();
1586 AI != AE; ++AI) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001587 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001588 ++i;
1589 }
1590
Jay Foad5bd375a2011-07-15 08:37:34 +00001591 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001592 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001593 CI->setCallingConv(F->getCallingConv());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001594 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001595 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001596 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001597 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001598 }
1599
1600 NewG->copyAttributesFrom(G);
1601 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001602 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001603 G->replaceAllUsesWith(NewG);
1604 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001605
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001606 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001607 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001608}
1609
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001610// Replace G with an alias to F and delete G.
1611void MergeFunctions::writeAlias(Function *F, Function *G) {
Rafael Espindola4fe00942014-05-16 13:34:04 +00001612 PointerType *PTy = G->getType();
David Blaikief64246b2015-04-29 21:22:39 +00001613 auto *GA = GlobalAlias::create(PTy, G->getLinkage(), "", F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001614 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1615 GA->takeName(G);
1616 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001617 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001618 G->replaceAllUsesWith(GA);
1619 G->eraseFromParent();
1620
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001621 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001622 ++NumAliasesWritten;
1623}
1624
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001625// Merge two equivalent functions. Upon completion, Function G is deleted.
1626void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Nick Lewycky71972d42010-09-07 01:42:10 +00001627 if (F->mayBeOverridden()) {
1628 assert(G->mayBeOverridden());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001629
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001630 // Make them both thunks to the same internal function.
1631 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1632 F->getParent());
1633 H->copyAttributesFrom(F);
1634 H->takeName(F);
1635 removeUsers(F);
1636 F->replaceAllUsesWith(H);
1637
1638 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1639
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001640 if (HasGlobalAliases) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001641 writeAlias(F, G);
1642 writeAlias(F, H);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001643 } else {
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001644 writeThunk(F, G);
1645 writeThunk(F, H);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001646 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001647
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001648 F->setAlignment(MaxAlignment);
1649 F->setLinkage(GlobalValue::PrivateLinkage);
Nick Lewycky71972d42010-09-07 01:42:10 +00001650 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001651 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001652 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001653 }
1654
Nick Lewyckye04dc222009-06-12 08:04:51 +00001655 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001656}
1657
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001658/// Replace function F for function G in the map.
1659void MergeFunctions::replaceFunctionInTree(FnTreeType::iterator &IterToF,
1660 Function *G) {
1661 Function *F = IterToF->getFunc();
1662
1663 // A total order is already guaranteed otherwise because we process strong
1664 // functions before weak functions.
Denis Protivenskyc09e3762015-06-09 09:28:37 +00001665 assert(((F->mayBeOverridden() && G->mayBeOverridden()) ||
1666 (!F->mayBeOverridden() && !G->mayBeOverridden())) &&
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001667 "Only change functions if both are strong or both are weak");
Arnold Schwaighofer003c2e92015-06-09 00:17:40 +00001668 (void)F;
JF Bastien057292a2015-08-21 23:27:24 +00001669 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
1670 "The two functions must be equal");
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001671
1672 IterToF->replaceBy(G);
1673}
1674
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001675// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001676// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001677bool MergeFunctions::insert(Function *NewFunction) {
1678 std::pair<FnTreeType::iterator, bool> Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001679 FnTree.insert(FunctionNode(NewFunction));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001680
Nick Lewycky292e78c2011-02-09 06:32:02 +00001681 if (Result.second) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001682 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001683 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001684 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001685
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +00001686 const FunctionNode &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001687
Matt Arsenault517d84e2013-10-01 18:05:30 +00001688 // Don't merge tiny functions, since it can just end up making the function
1689 // larger.
1690 // FIXME: Should still merge them if they are unnamed_addr and produce an
1691 // alias.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001692 if (NewFunction->size() == 1) {
1693 if (NewFunction->front().size() <= 2) {
1694 DEBUG(dbgs() << NewFunction->getName()
1695 << " is to small to bother merging\n");
Matt Arsenault517d84e2013-10-01 18:05:30 +00001696 return false;
1697 }
1698 }
1699
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001700 // Impose a total order (by name) on the replacement of functions. This is
1701 // important when operating on more than one module independently to prevent
1702 // cycles of thunks calling each other when the modules are linked together.
1703 //
1704 // When one function is weak and the other is strong there is an order imposed
1705 // already. We process strong functions before weak functions.
1706 if ((OldF.getFunc()->mayBeOverridden() && NewFunction->mayBeOverridden()) ||
1707 (!OldF.getFunc()->mayBeOverridden() && !NewFunction->mayBeOverridden()))
1708 if (OldF.getFunc()->getName() > NewFunction->getName()) {
1709 // Swap the two functions.
1710 Function *F = OldF.getFunc();
1711 replaceFunctionInTree(Result.first, NewFunction);
1712 NewFunction = F;
1713 assert(OldF.getFunc() != F && "Must have swapped the functions.");
1714 }
1715
Nick Lewycky00959372010-09-05 08:22:49 +00001716 // Never thunk a strong function to a weak function.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001717 assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden());
Nick Lewycky00959372010-09-05 08:22:49 +00001718
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001719 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
1720 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001721
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001722 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001723 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001724 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001725}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001726
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001727// Remove a function from FnTree. If it was already in FnTree, add
1728// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001729void MergeFunctions::remove(Function *F) {
Nick Lewycky292e78c2011-02-09 06:32:02 +00001730 // We need to make sure we remove F, not a function "equal" to F per the
1731 // function equality comparator.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001732 FnTreeType::iterator found = FnTree.find(FunctionNode(F));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001733 size_t Erased = 0;
1734 if (found != FnTree.end() && found->getFunc() == F) {
1735 Erased = 1;
1736 FnTree.erase(found);
1737 }
1738
1739 if (Erased) {
1740 DEBUG(dbgs() << "Removed " << F->getName()
1741 << " from set and deferred it.\n");
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001742 Deferred.emplace_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001743 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001744}
Nick Lewycky00959372010-09-05 08:22:49 +00001745
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001746// For each instruction used by the value, remove() the function that contains
1747// the instruction. This should happen right before a call to RAUW.
1748void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001749 std::vector<Value *> Worklist;
1750 Worklist.push_back(V);
JF Bastien7289f732015-07-15 21:51:33 +00001751 SmallSet<Value*, 8> Visited;
1752 Visited.insert(V);
Nick Lewycky5361b842011-01-02 19:16:44 +00001753 while (!Worklist.empty()) {
1754 Value *V = Worklist.back();
1755 Worklist.pop_back();
1756
Chandler Carruthcdf47882014-03-09 03:16:01 +00001757 for (User *U : V->users()) {
1758 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001759 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001760 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001761 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001762 } else if (Constant *C = dyn_cast<Constant>(U)) {
JF Bastien7289f732015-07-15 21:51:33 +00001763 for (User *UU : C->users()) {
1764 if (!Visited.insert(UU).second)
1765 Worklist.push_back(UU);
1766 }
Nick Lewycky5361b842011-01-02 19:16:44 +00001767 }
Nick Lewycky00959372010-09-05 08:22:49 +00001768 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001769 }
Nick Lewycky00959372010-09-05 08:22:49 +00001770}