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