blob: 726786a7f7132a8f03bdb1499fa97cbff66f5e39 [file] [log] [blame]
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001//===- MergeFunctions.cpp - Merge identical functions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass looks for equivalent functions that are mergable and folds them.
11//
Stepan Dyatkovskiy471eab32014-06-22 00:57:09 +000012// Order relation is defined on set of functions. It was made through
13// special function comparison procedure that returns
14// 0 when functions are equal,
15// -1 when Left function is less than right function, and
16// 1 for opposite case. We need total-ordering, so we need to maintain
17// four properties on the functions set:
18// a <= a (reflexivity)
19// if a <= b and b <= a then a = b (antisymmetry)
20// if a <= b and b <= c then a <= c (transitivity).
21// for all a and b: a <= b or b <= a (totality).
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000022//
Stepan Dyatkovskiy471eab32014-06-22 00:57:09 +000023// Comparison iterates through each instruction in each basic block.
24// Functions are kept on binary tree. For each new function F we perform
25// lookup in binary tree.
26// In practice it works the following way:
27// -- We define Function* container class with custom "operator<" (FunctionPtr).
28// -- "FunctionPtr" instances are stored in std::set collection, so every
29// std::set::insert operation will give you result in log(N) time.
JF Bastien5e4303d2015-08-15 01:18:18 +000030//
31// As an optimization, a hash of the function structure is calculated first, and
32// two functions are only compared if they have the same hash. This hash is
33// cheap to compute, and has the property that if function F == G according to
34// the comparison function, then hash(F) == hash(G). This consistency property
35// is critical to ensuring all possible merging opportunities are exploited.
36// Collisions in the hash affect the speed of the pass but not the correctness
37// or determinism of the resulting transformation.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000038//
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000039// When a match is found the functions are folded. If both functions are
40// overridable, we move the functionality into a new internal function and
41// leave two overridable thunks to it.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000042//
43//===----------------------------------------------------------------------===//
44//
45// Future work:
46//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000047// * virtual functions.
48//
49// Many functions have their address taken by the virtual function table for
50// the object they belong to. However, as long as it's only used for a lookup
Nick Lewyckyfbd27572010-08-08 05:04:23 +000051// and call, this is irrelevant, and we'd like to fold such functions.
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000052//
Nick Lewyckyfbd27572010-08-08 05:04:23 +000053// * be smarter about bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000054//
55// In order to fold functions, we will sometimes add either bitcast instructions
56// or bitcast constant expressions. Unfortunately, this can confound further
57// analysis since the two functions differ where one has a bitcast and the
Nick Lewyckyfbd27572010-08-08 05:04:23 +000058// other doesn't. We should learn to look through bitcasts.
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +000059//
Stepan Dyatkovskiy471eab32014-06-22 00:57:09 +000060// * Compare complex types with pointer types inside.
61// * Compare cross-reference cases.
62// * Compare complex expressions.
63//
64// All the three issues above could be described as ability to prove that
65// fA == fB == fC == fE == fF == fG in example below:
66//
67// void fA() {
68// fB();
69// }
70// void fB() {
71// fA();
72// }
73//
74// void fE() {
75// fF();
76// }
77// void fF() {
78// fG();
79// }
80// void fG() {
81// fE();
82// }
83//
84// Simplest cross-reference case (fA <--> fB) was implemented in previous
85// versions of MergeFunctions, though it presented only in two function pairs
86// in test-suite (that counts >50k functions)
87// Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
88// could cover much more cases.
89//
Nick Lewyckyd01d42e2008-11-02 05:52:50 +000090//===----------------------------------------------------------------------===//
91
Mehdi Aminib550cb12016-04-18 09:17:29 +000092#include "llvm/ADT/Hashing.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000093#include "llvm/ADT/STLExtras.h"
94#include "llvm/ADT/SmallSet.h"
95#include "llvm/ADT/Statistic.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000096#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000097#include "llvm/IR/Constants.h"
98#include "llvm/IR/DataLayout.h"
99#include "llvm/IR/IRBuilder.h"
100#include "llvm/IR/InlineAsm.h"
101#include "llvm/IR/Instructions.h"
102#include "llvm/IR/LLVMContext.h"
103#include "llvm/IR/Module.h"
104#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +0000105#include "llvm/IR/ValueHandle.h"
JF Bastien057292a2015-08-21 23:27:24 +0000106#include "llvm/IR/ValueMap.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000107#include "llvm/Pass.h"
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000108#include "llvm/Support/CommandLine.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000109#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +0000110#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000111#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +0000112#include "llvm/Transforms/IPO.h"
Nick Lewycky68984ed2010-08-31 08:29:37 +0000113#include <vector>
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000114
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000115using namespace llvm;
116
Chandler Carruth964daaa2014-04-22 02:55:47 +0000117#define DEBUG_TYPE "mergefunc"
118
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000119STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +0000120STATISTIC(NumThunksWritten, "Number of thunks generated");
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000121STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky71972d42010-09-07 01:42:10 +0000122STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000123
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000124static cl::opt<unsigned> NumFunctionsForSanityCheck(
125 "mergefunc-sanity",
126 cl::desc("How many functions in module could be used for "
127 "MergeFunctions pass sanity check. "
128 "'0' disables this check. Works only with '-debug' key."),
129 cl::init(0), cl::Hidden);
130
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000131namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000132
JF Bastien057292a2015-08-21 23:27:24 +0000133/// GlobalNumberState assigns an integer to each global value in the program,
134/// which is used by the comparison routine to order references to globals. This
135/// state must be preserved throughout the pass, because Functions and other
136/// globals need to maintain their relative order. Globals are assigned a number
137/// when they are first visited. This order is deterministic, and so the
138/// assigned numbers are as well. When two functions are merged, neither number
139/// is updated. If the symbols are weak, this would be incorrect. If they are
140/// strong, then one will be replaced at all references to the other, and so
141/// direct callsites will now see one or the other symbol, and no update is
142/// necessary. Note that if we were guaranteed unique names, we could just
143/// compare those, but this would not work for stripped bitcodes or for those
144/// few symbols without a name.
145class GlobalNumberState {
146 struct Config : ValueMapConfig<GlobalValue*> {
147 enum { FollowRAUW = false };
148 };
149 // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW
150 // occurs, the mapping does not change. Tracking changes is unnecessary, and
151 // also problematic for weak symbols (which may be overwritten).
152 typedef ValueMap<GlobalValue *, uint64_t, Config> ValueNumberMap;
153 ValueNumberMap GlobalNumbers;
154 // The next unused serial number to assign to a global.
155 uint64_t NextNumber;
156 public:
157 GlobalNumberState() : GlobalNumbers(), NextNumber(0) {}
158 uint64_t getNumber(GlobalValue* Global) {
159 ValueNumberMap::iterator MapIter;
160 bool Inserted;
161 std::tie(MapIter, Inserted) = GlobalNumbers.insert({Global, NextNumber});
162 if (Inserted)
163 NextNumber++;
164 return MapIter->second;
165 }
Arnold Schwaighofer0591c5d2015-10-05 17:26:36 +0000166 void clear() {
167 GlobalNumbers.clear();
168 }
JF Bastien057292a2015-08-21 23:27:24 +0000169};
170
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000171/// FunctionComparator - Compares two functions to determine whether or not
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000172/// they will generate machine code with the same behaviour. DataLayout is
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000173/// used if available. The comparator always fails conservatively (erring on the
174/// side of claiming that two functions are different).
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000175class FunctionComparator {
176public:
JF Bastien057292a2015-08-21 23:27:24 +0000177 FunctionComparator(const Function *F1, const Function *F2,
178 GlobalNumberState* GN)
179 : FnL(F1), FnR(F2), GlobalNumbers(GN) {}
Nick Lewyckye04dc222009-06-12 08:04:51 +0000180
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000181 /// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000182 int compare();
JF Bastien5e4303d2015-08-15 01:18:18 +0000183 /// Hash a function. Equivalent functions will have the same hash, and unequal
184 /// functions will have different hashes with high probability.
185 typedef uint64_t FunctionHash;
186 static FunctionHash functionHash(Function &);
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000187
188private:
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000189 /// Test whether two basic blocks have equivalent behaviour.
JF Bastien83314582016-04-13 21:12:21 +0000190 int cmpBasicBlocks(const BasicBlock *BBL, const BasicBlock *BBR) const;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000191
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000192 /// Constants comparison.
193 /// Its analog to lexicographical comparison between hypothetical numbers
194 /// of next format:
195 /// <bitcastability-trait><raw-bit-contents>
196 ///
197 /// 1. Bitcastability.
198 /// Check whether L's type could be losslessly bitcasted to R's type.
199 /// On this stage method, in case when lossless bitcast is not possible
200 /// method returns -1 or 1, thus also defining which type is greater in
201 /// context of bitcastability.
202 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
203 /// to the contents comparison.
204 /// If types differ, remember types comparison result and check
205 /// whether we still can bitcast types.
206 /// Stage 1: Types that satisfies isFirstClassType conditions are always
207 /// greater then others.
208 /// Stage 2: Vector is greater then non-vector.
209 /// If both types are vectors, then vector with greater bitwidth is
210 /// greater.
211 /// If both types are vectors with the same bitwidth, then types
212 /// are bitcastable, and we can skip other stages, and go to contents
213 /// comparison.
214 /// Stage 3: Pointer types are greater than non-pointers. If both types are
215 /// pointers of the same address space - go to contents comparison.
216 /// Different address spaces: pointer with greater address space is
217 /// greater.
218 /// Stage 4: Types are neither vectors, nor pointers. And they differ.
219 /// We don't know how to bitcast them. So, we better don't do it,
220 /// and return types comparison result (so it determines the
221 /// relationship among constants we don't know how to bitcast).
222 ///
223 /// Just for clearance, let's see how the set of constants could look
224 /// on single dimension axis:
225 ///
226 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
227 /// Where: NFCT - Not a FirstClassType
228 /// FCT - FirstClassTyp:
229 ///
230 /// 2. Compare raw contents.
231 /// It ignores types on this stage and only compares bits from L and R.
232 /// Returns 0, if L and R has equivalent contents.
233 /// -1 or 1 if values are different.
234 /// Pretty trivial:
235 /// 2.1. If contents are numbers, compare numbers.
236 /// Ints with greater bitwidth are greater. Ints with same bitwidths
237 /// compared by their contents.
238 /// 2.2. "And so on". Just to avoid discrepancies with comments
239 /// perhaps it would be better to read the implementation itself.
240 /// 3. And again about overall picture. Let's look back at how the ordered set
241 /// of constants will look like:
242 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
243 ///
244 /// Now look, what could be inside [FCT, "others"], for example:
245 /// [FCT, "others"] =
246 /// [
247 /// [double 0.1], [double 1.23],
248 /// [i32 1], [i32 2],
249 /// { double 1.0 }, ; StructTyID, NumElements = 1
250 /// { i32 1 }, ; StructTyID, NumElements = 1
251 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
252 /// { i32 1, double 1 } ; StructTyID, NumElements = 2
253 /// ]
254 ///
255 /// Let's explain the order. Float numbers will be less than integers, just
256 /// because of cmpType terms: FloatTyID < IntegerTyID.
257 /// Floats (with same fltSemantics) are sorted according to their value.
258 /// Then you can see integers, and they are, like a floats,
259 /// could be easy sorted among each others.
260 /// The structures. Structures are grouped at the tail, again because of their
261 /// TypeID: StructTyID > IntegerTyID > FloatTyID.
262 /// Structures with greater number of elements are greater. Structures with
263 /// greater elements going first are greater.
264 /// The same logic with vectors, arrays and other possible complex types.
265 ///
266 /// Bitcastable constants.
267 /// Let's assume, that some constant, belongs to some group of
268 /// "so-called-equal" values with different types, and at the same time
269 /// belongs to another group of constants with equal types
270 /// and "really" equal values.
271 ///
272 /// Now, prove that this is impossible:
273 ///
274 /// If constant A with type TyA is bitcastable to B with type TyB, then:
275 /// 1. All constants with equal types to TyA, are bitcastable to B. Since
276 /// those should be vectors (if TyA is vector), pointers
277 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
278 /// be equal to TyB.
279 /// 2. All constants with non-equal, but bitcastable types to TyA, are
280 /// bitcastable to B.
281 /// Once again, just because we allow it to vectors and pointers only.
282 /// This statement could be expanded as below:
283 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
284 /// vector B, and thus bitcastable to B as well.
285 /// 2.2. All pointers of the same address space, no matter what they point to,
286 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
287 /// So any constant equal or bitcastable to A is equal or bitcastable to B.
288 /// QED.
289 ///
290 /// In another words, for pointers and vectors, we ignore top-level type and
291 /// look at their particular properties (bit-width for vectors, and
292 /// address space for pointers).
293 /// If these properties are equal - compare their contents.
JF Bastien83314582016-04-13 21:12:21 +0000294 int cmpConstants(const Constant *L, const Constant *R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000295
JF Bastien057292a2015-08-21 23:27:24 +0000296 /// Compares two global values by number. Uses the GlobalNumbersState to
297 /// identify the same gobals across function calls.
JF Bastien83314582016-04-13 21:12:21 +0000298 int cmpGlobalValues(GlobalValue *L, GlobalValue *R) const;
JF Bastien057292a2015-08-21 23:27:24 +0000299
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000300 /// Assign or look up previously assigned numbers for the two values, and
301 /// return whether the numbers are equal. Numbers are assigned in the order
302 /// visited.
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000303 /// Comparison order:
304 /// Stage 0: Value that is function itself is always greater then others.
305 /// If left and right values are references to their functions, then
306 /// they are equal.
307 /// Stage 1: Constants are greater than non-constants.
308 /// If both left and right are constants, then the result of
309 /// cmpConstants is used as cmpValues result.
310 /// Stage 2: InlineAsm instances are greater than others. If both left and
311 /// right are InlineAsm instances, InlineAsm* pointers casted to
312 /// integers and compared as numbers.
313 /// Stage 3: For all other cases we compare order we meet these values in
314 /// their functions. If right value was met first during scanning,
315 /// then left value is greater.
316 /// In another words, we compare serial numbers, for more details
317 /// see comments for sn_mapL and sn_mapR.
JF Bastien83314582016-04-13 21:12:21 +0000318 int cmpValues(const Value *L, const Value *R) const;
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000319
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000320 /// Compare two Instructions for equivalence, similar to
JF Bastien1bb32ac2016-04-12 21:13:01 +0000321 /// Instruction::isSameOperationAs.
322 ///
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000323 /// Stages are listed in "most significant stage first" order:
324 /// On each stage below, we do comparison between some left and right
325 /// operation parts. If parts are non-equal, we assign parts comparison
326 /// result to the operation comparison result and exit from method.
327 /// Otherwise we proceed to the next stage.
328 /// Stages:
329 /// 1. Operations opcodes. Compared as numbers.
330 /// 2. Number of operands.
331 /// 3. Operation types. Compared with cmpType method.
332 /// 4. Compare operation subclass optional data as stream of bytes:
333 /// just convert it to integers and call cmpNumbers.
334 /// 5. Compare in operation operand types with cmpType in
335 /// most significant operand first order.
336 /// 6. Last stage. Check operations for some specific attributes.
337 /// For example, for Load it would be:
338 /// 6.1.Load: volatile (as boolean flag)
339 /// 6.2.Load: alignment (as integer numbers)
JF Bastien1bb32ac2016-04-12 21:13:01 +0000340 /// 6.3.Load: ordering (as underlying enum class value)
341 /// 6.4.Load: synch-scope (as integer numbers)
342 /// 6.5.Load: range metadata (as integer ranges)
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000343 /// On this stage its better to see the code, since its not more than 10-15
344 /// strings for particular instruction, and could change sometimes.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000345 int cmpOperations(const Instruction *L, const Instruction *R) const;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000346
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000347 /// Compare two GEPs for equivalent pointer arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000348 /// Parts to be compared for each comparison stage,
349 /// most significant stage first:
350 /// 1. Address space. As numbers.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000351 /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000352 /// 3. Pointer operand type (using cmpType method).
353 /// 4. Number of operands.
354 /// 5. Compare operands, using cmpValues method.
JF Bastien83314582016-04-13 21:12:21 +0000355 int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR) const;
356 int cmpGEPs(const GetElementPtrInst *GEPL,
357 const GetElementPtrInst *GEPR) const {
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +0000358 return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +0000359 }
360
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000361 /// cmpType - compares two types,
362 /// defines total ordering among the types set.
363 ///
364 /// Return values:
365 /// 0 if types are equal,
366 /// -1 if Left is less than Right,
367 /// +1 if Left is greater than Right.
368 ///
369 /// Description:
370 /// Comparison is broken onto stages. Like in lexicographical comparison
371 /// stage coming first has higher priority.
372 /// On each explanation stage keep in mind total ordering properties.
373 ///
Stepan Dyatkovskiy90c44362014-03-14 08:17:19 +0000374 /// 0. Before comparison we coerce pointer types of 0 address space to
375 /// integer.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000376 /// We also don't bother with same type at left and right, so
377 /// just return 0 in this case.
378 ///
379 /// 1. If types are of different kind (different type IDs).
380 /// Return result of type IDs comparison, treating them as numbers.
JF Bastien057292a2015-08-21 23:27:24 +0000381 /// 2. If types are integers, check that they have the same width. If they
382 /// are vectors, check that they have the same count and subtype.
383 /// 3. Types have the same ID, so check whether they are one of:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000384 /// * Void
385 /// * Float
386 /// * Double
387 /// * X86_FP80
388 /// * FP128
389 /// * PPC_FP128
390 /// * Label
391 /// * Metadata
JF Bastien057292a2015-08-21 23:27:24 +0000392 /// We can treat these types as equal whenever their IDs are same.
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000393 /// 4. If Left and Right are pointers, return result of address space
394 /// comparison (numbers comparison). We can treat pointer types of same
395 /// address space as equal.
396 /// 5. If types are complex.
397 /// Then both Left and Right are to be expanded and their element types will
398 /// be checked with the same way. If we get Res != 0 on some stage, return it.
399 /// Otherwise return 0.
400 /// 6. For all other cases put llvm_unreachable.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000401 int cmpTypes(Type *TyL, Type *TyR) const;
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000402
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000403 int cmpNumbers(uint64_t L, uint64_t R) const;
JF Bastien800f87a2016-04-06 21:19:33 +0000404 int cmpOrderings(AtomicOrdering L, AtomicOrdering R) const;
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000405 int cmpAPInts(const APInt &L, const APInt &R) const;
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000406 int cmpAPFloats(const APFloat &L, const APFloat &R) const;
JF Bastien057292a2015-08-21 23:27:24 +0000407 int cmpInlineAsm(const InlineAsm *L, const InlineAsm *R) const;
408 int cmpMem(StringRef L, StringRef R) const;
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000409 int cmpAttrs(const AttributeSet L, const AttributeSet R) const;
JF Bastien83314582016-04-13 21:12:21 +0000410 int cmpRangeMetadata(const MDNode *L, const MDNode *R) const;
Sanjoy Das2a74eb02015-12-14 19:11:40 +0000411 int cmpOperandBundlesSchema(const Instruction *L, const Instruction *R) const;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000412
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000413 // The two functions undergoing comparison.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +0000414 const Function *FnL, *FnR;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000415
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +0000416 /// Assign serial numbers to values from left function, and values from
417 /// right function.
418 /// Explanation:
419 /// Being comparing functions we need to compare values we meet at left and
420 /// right sides.
421 /// Its easy to sort things out for external values. It just should be
422 /// the same value at left and right.
423 /// But for local values (those were introduced inside function body)
424 /// we have to ensure they were introduced at exactly the same place,
425 /// and plays the same role.
426 /// Let's assign serial number to each value when we meet it first time.
427 /// Values that were met at same place will be with same serial numbers.
428 /// In this case it would be good to explain few points about values assigned
429 /// to BBs and other ways of implementation (see below).
430 ///
431 /// 1. Safety of BB reordering.
432 /// It's safe to change the order of BasicBlocks in function.
433 /// Relationship with other functions and serial numbering will not be
434 /// changed in this case.
435 /// As follows from FunctionComparator::compare(), we do CFG walk: we start
436 /// from the entry, and then take each terminator. So it doesn't matter how in
437 /// fact BBs are ordered in function. And since cmpValues are called during
438 /// this walk, the numbering depends only on how BBs located inside the CFG.
439 /// So the answer is - yes. We will get the same numbering.
440 ///
441 /// 2. Impossibility to use dominance properties of values.
442 /// If we compare two instruction operands: first is usage of local
443 /// variable AL from function FL, and second is usage of local variable AR
444 /// from FR, we could compare their origins and check whether they are
445 /// defined at the same place.
446 /// But, we are still not able to compare operands of PHI nodes, since those
447 /// could be operands from further BBs we didn't scan yet.
448 /// So it's impossible to use dominance properties in general.
JF Bastien83314582016-04-13 21:12:21 +0000449 mutable DenseMap<const Value*, int> sn_mapL, sn_mapR;
JF Bastien057292a2015-08-21 23:27:24 +0000450
451 // The global state we will use
452 GlobalNumberState* GlobalNumbers;
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000453};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000454
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000455class FunctionNode {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000456 mutable AssertingVH<Function> F;
JF Bastien5e4303d2015-08-15 01:18:18 +0000457 FunctionComparator::FunctionHash Hash;
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000458public:
JF Bastien5e4303d2015-08-15 01:18:18 +0000459 // Note the hash is recalculated potentially multiple times, but it is cheap.
JF Bastien057292a2015-08-21 23:27:24 +0000460 FunctionNode(Function *F)
461 : F(F), Hash(FunctionComparator::functionHash(*F)) {}
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000462 Function *getFunc() const { return F; }
JF Bastien057292a2015-08-21 23:27:24 +0000463 FunctionComparator::FunctionHash getHash() const { return Hash; }
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000464
465 /// Replace the reference to the function F by the function G, assuming their
466 /// implementations are equal.
467 void replaceBy(Function *G) const {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000468 F = G;
469 }
470
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000471 void release() { F = nullptr; }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000472};
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000473} // end anonymous namespace
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +0000474
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000475int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const {
476 if (L < R) return -1;
477 if (L > R) return 1;
478 return 0;
479}
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000480
JF Bastien800f87a2016-04-06 21:19:33 +0000481int FunctionComparator::cmpOrderings(AtomicOrdering L, AtomicOrdering R) const {
482 if ((int)L < (int)R) return -1;
483 if ((int)L > (int)R) return 1;
484 return 0;
485}
486
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000487int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const {
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000488 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth()))
489 return Res;
490 if (L.ugt(R)) return 1;
491 if (R.ugt(L)) return -1;
492 return 0;
493}
494
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000495int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const {
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000496 // Floats are ordered first by semantics (i.e. float, double, half, etc.),
497 // then by value interpreted as a bitstring (aka APInt).
JF Bastien057292a2015-08-21 23:27:24 +0000498 const fltSemantics &SL = L.getSemantics(), &SR = R.getSemantics();
499 if (int Res = cmpNumbers(APFloat::semanticsPrecision(SL),
500 APFloat::semanticsPrecision(SR)))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000501 return Res;
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000502 if (int Res = cmpNumbers(APFloat::semanticsMaxExponent(SL),
503 APFloat::semanticsMaxExponent(SR)))
504 return Res;
505 if (int Res = cmpNumbers(APFloat::semanticsMinExponent(SL),
506 APFloat::semanticsMinExponent(SR)))
507 return Res;
508 if (int Res = cmpNumbers(APFloat::semanticsSizeInBits(SL),
509 APFloat::semanticsSizeInBits(SR)))
510 return Res;
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000511 return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt());
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000512}
513
JF Bastien057292a2015-08-21 23:27:24 +0000514int FunctionComparator::cmpMem(StringRef L, StringRef R) const {
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000515 // Prevent heavy comparison, compare sizes first.
516 if (int Res = cmpNumbers(L.size(), R.size()))
517 return Res;
518
519 // Compare strings lexicographically only when it is necessary: only when
520 // strings are equal in size.
521 return L.compare(R);
522}
523
524int FunctionComparator::cmpAttrs(const AttributeSet L,
525 const AttributeSet R) const {
526 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots()))
527 return Res;
528
529 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) {
530 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i),
531 RE = R.end(i);
532 for (; LI != LE && RI != RE; ++LI, ++RI) {
533 Attribute LA = *LI;
534 Attribute RA = *RI;
535 if (LA < RA)
536 return -1;
537 if (RA < LA)
538 return 1;
539 }
540 if (LI != LE)
541 return 1;
542 if (RI != RE)
543 return -1;
544 }
545 return 0;
546}
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000547
JF Bastien83314582016-04-13 21:12:21 +0000548int FunctionComparator::cmpRangeMetadata(const MDNode *L,
549 const MDNode *R) const {
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000550 if (L == R)
551 return 0;
552 if (!L)
553 return -1;
554 if (!R)
555 return 1;
556 // Range metadata is a sequence of numbers. Make sure they are the same
JF Bastien83314582016-04-13 21:12:21 +0000557 // sequence.
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000558 // TODO: Note that as this is metadata, it is possible to drop and/or merge
559 // this data when considering functions to merge. Thus this comparison would
560 // return 0 (i.e. equivalent), but merging would become more complicated
561 // because the ranges would need to be unioned. It is not likely that
562 // functions differ ONLY in this metadata if they are actually the same
563 // function semantically.
564 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
565 return Res;
566 for (size_t I = 0; I < L->getNumOperands(); ++I) {
JF Bastien83314582016-04-13 21:12:21 +0000567 ConstantInt *LLow = mdconst::extract<ConstantInt>(L->getOperand(I));
568 ConstantInt *RLow = mdconst::extract<ConstantInt>(R->getOperand(I));
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000569 if (int Res = cmpAPInts(LLow->getValue(), RLow->getValue()))
570 return Res;
571 }
572 return 0;
573}
Stepan Dyatkovskiy5c2cc252014-05-16 08:55:34 +0000574
Sanjoy Das2a74eb02015-12-14 19:11:40 +0000575int FunctionComparator::cmpOperandBundlesSchema(const Instruction *L,
576 const Instruction *R) const {
577 ImmutableCallSite LCS(L);
578 ImmutableCallSite RCS(R);
579
580 assert(LCS && RCS && "Must be calls or invokes!");
581 assert(LCS.isCall() == RCS.isCall() && "Can't compare otherwise!");
582
583 if (int Res =
584 cmpNumbers(LCS.getNumOperandBundles(), RCS.getNumOperandBundles()))
585 return Res;
586
587 for (unsigned i = 0, e = LCS.getNumOperandBundles(); i != e; ++i) {
588 auto OBL = LCS.getOperandBundleAt(i);
589 auto OBR = RCS.getOperandBundleAt(i);
590
591 if (int Res = OBL.getTagName().compare(OBR.getTagName()))
592 return Res;
593
594 if (int Res = cmpNumbers(OBL.Inputs.size(), OBR.Inputs.size()))
595 return Res;
596 }
597
598 return 0;
599}
600
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000601/// Constants comparison:
602/// 1. Check whether type of L constant could be losslessly bitcasted to R
603/// type.
604/// 2. Compare constant contents.
605/// For more details see declaration comments.
JF Bastien83314582016-04-13 21:12:21 +0000606int FunctionComparator::cmpConstants(const Constant *L,
607 const Constant *R) const {
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000608
609 Type *TyL = L->getType();
610 Type *TyR = R->getType();
611
612 // Check whether types are bitcastable. This part is just re-factored
613 // Type::canLosslesslyBitCastTo method, but instead of returning true/false,
614 // we also pack into result which type is "less" for us.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000615 int TypesRes = cmpTypes(TyL, TyR);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000616 if (TypesRes != 0) {
617 // Types are different, but check whether we can bitcast them.
618 if (!TyL->isFirstClassType()) {
619 if (TyR->isFirstClassType())
620 return -1;
621 // Neither TyL nor TyR are values of first class type. Return the result
622 // of comparing the types
623 return TypesRes;
624 }
625 if (!TyR->isFirstClassType()) {
626 if (TyL->isFirstClassType())
627 return 1;
628 return TypesRes;
629 }
630
631 // Vector -> Vector conversions are always lossless if the two vector types
632 // have the same size, otherwise not.
633 unsigned TyLWidth = 0;
634 unsigned TyRWidth = 0;
635
Craig Toppere3dcce92015-08-01 22:20:21 +0000636 if (auto *VecTyL = dyn_cast<VectorType>(TyL))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000637 TyLWidth = VecTyL->getBitWidth();
Craig Toppere3dcce92015-08-01 22:20:21 +0000638 if (auto *VecTyR = dyn_cast<VectorType>(TyR))
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000639 TyRWidth = VecTyR->getBitWidth();
640
641 if (TyLWidth != TyRWidth)
642 return cmpNumbers(TyLWidth, TyRWidth);
643
644 // Zero bit-width means neither TyL nor TyR are vectors.
645 if (!TyLWidth) {
646 PointerType *PTyL = dyn_cast<PointerType>(TyL);
647 PointerType *PTyR = dyn_cast<PointerType>(TyR);
648 if (PTyL && PTyR) {
649 unsigned AddrSpaceL = PTyL->getAddressSpace();
650 unsigned AddrSpaceR = PTyR->getAddressSpace();
651 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR))
652 return Res;
653 }
654 if (PTyL)
655 return 1;
656 if (PTyR)
657 return -1;
658
659 // TyL and TyR aren't vectors, nor pointers. We don't know how to
660 // bitcast them.
661 return TypesRes;
662 }
663 }
664
665 // OK, types are bitcastable, now check constant contents.
666
667 if (L->isNullValue() && R->isNullValue())
668 return TypesRes;
669 if (L->isNullValue() && !R->isNullValue())
670 return 1;
671 if (!L->isNullValue() && R->isNullValue())
672 return -1;
673
JF Bastien057292a2015-08-21 23:27:24 +0000674 auto GlobalValueL = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(L));
675 auto GlobalValueR = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(R));
676 if (GlobalValueL && GlobalValueR) {
677 return cmpGlobalValues(GlobalValueL, GlobalValueR);
678 }
679
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000680 if (int Res = cmpNumbers(L->getValueID(), R->getValueID()))
681 return Res;
682
JF Bastien057292a2015-08-21 23:27:24 +0000683 if (const auto *SeqL = dyn_cast<ConstantDataSequential>(L)) {
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000684 const auto *SeqR = cast<ConstantDataSequential>(R);
JF Bastien057292a2015-08-21 23:27:24 +0000685 // This handles ConstantDataArray and ConstantDataVector. Note that we
686 // compare the two raw data arrays, which might differ depending on the host
687 // endianness. This isn't a problem though, because the endiness of a module
688 // will affect the order of the constants, but this order is the same
689 // for a given input module and host platform.
690 return cmpMem(SeqL->getRawDataValues(), SeqR->getRawDataValues());
691 }
692
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000693 switch (L->getValueID()) {
David Majnemerf0f224d2015-11-11 21:57:16 +0000694 case Value::UndefValueVal:
695 case Value::ConstantTokenNoneVal:
696 return TypesRes;
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000697 case Value::ConstantIntVal: {
698 const APInt &LInt = cast<ConstantInt>(L)->getValue();
699 const APInt &RInt = cast<ConstantInt>(R)->getValue();
Stepan Dyatkovskiy7f895c12014-08-25 08:19:50 +0000700 return cmpAPInts(LInt, RInt);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000701 }
702 case Value::ConstantFPVal: {
703 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF();
704 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF();
Stepan Dyatkovskiyc90308b2014-08-25 08:22:46 +0000705 return cmpAPFloats(LAPF, RAPF);
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000706 }
707 case Value::ConstantArrayVal: {
708 const ConstantArray *LA = cast<ConstantArray>(L);
709 const ConstantArray *RA = cast<ConstantArray>(R);
710 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements();
711 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements();
712 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
713 return Res;
714 for (uint64_t i = 0; i < NumElementsL; ++i) {
715 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)),
716 cast<Constant>(RA->getOperand(i))))
717 return Res;
718 }
719 return 0;
720 }
721 case Value::ConstantStructVal: {
722 const ConstantStruct *LS = cast<ConstantStruct>(L);
723 const ConstantStruct *RS = cast<ConstantStruct>(R);
724 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements();
725 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements();
726 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
727 return Res;
728 for (unsigned i = 0; i != NumElementsL; ++i) {
729 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)),
730 cast<Constant>(RS->getOperand(i))))
731 return Res;
732 }
733 return 0;
734 }
735 case Value::ConstantVectorVal: {
736 const ConstantVector *LV = cast<ConstantVector>(L);
737 const ConstantVector *RV = cast<ConstantVector>(R);
738 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements();
739 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements();
740 if (int Res = cmpNumbers(NumElementsL, NumElementsR))
741 return Res;
742 for (uint64_t i = 0; i < NumElementsL; ++i) {
743 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)),
744 cast<Constant>(RV->getOperand(i))))
745 return Res;
746 }
747 return 0;
748 }
749 case Value::ConstantExprVal: {
750 const ConstantExpr *LE = cast<ConstantExpr>(L);
751 const ConstantExpr *RE = cast<ConstantExpr>(R);
752 unsigned NumOperandsL = LE->getNumOperands();
753 unsigned NumOperandsR = RE->getNumOperands();
754 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR))
755 return Res;
756 for (unsigned i = 0; i < NumOperandsL; ++i) {
757 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)),
758 cast<Constant>(RE->getOperand(i))))
759 return Res;
760 }
761 return 0;
762 }
JF Bastien057292a2015-08-21 23:27:24 +0000763 case Value::BlockAddressVal: {
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000764 const BlockAddress *LBA = cast<BlockAddress>(L);
765 const BlockAddress *RBA = cast<BlockAddress>(R);
766 if (int Res = cmpValues(LBA->getFunction(), RBA->getFunction()))
767 return Res;
768 if (LBA->getFunction() == RBA->getFunction()) {
769 // They are BBs in the same function. Order by which comes first in the
770 // BB order of the function. This order is deterministic.
771 Function* F = LBA->getFunction();
772 BasicBlock *LBB = LBA->getBasicBlock();
773 BasicBlock *RBB = RBA->getBasicBlock();
774 if (LBB == RBB)
775 return 0;
776 for(BasicBlock &BB : F->getBasicBlockList()) {
777 if (&BB == LBB) {
778 assert(&BB != RBB);
779 return -1;
780 }
781 if (&BB == RBB)
782 return 1;
783 }
784 llvm_unreachable("Basic Block Address does not point to a basic block in "
785 "its function.");
786 return -1;
787 } else {
788 // cmpValues said the functions are the same. So because they aren't
789 // literally the same pointer, they must respectively be the left and
790 // right functions.
791 assert(LBA->getFunction() == FnL && RBA->getFunction() == FnR);
792 // cmpValues will tell us if these are equivalent BasicBlocks, in the
793 // context of their respective functions.
794 return cmpValues(LBA->getBasicBlock(), RBA->getBasicBlock());
795 }
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000796 }
JF Bastien057292a2015-08-21 23:27:24 +0000797 default: // Unknown constant, abort.
798 DEBUG(dbgs() << "Looking at valueID " << L->getValueID() << "\n");
799 llvm_unreachable("Constant ValueID not recognized.");
800 return -1;
801 }
802}
803
JF Bastien83314582016-04-13 21:12:21 +0000804int FunctionComparator::cmpGlobalValues(GlobalValue *L, GlobalValue *R) const {
JF Bastien057292a2015-08-21 23:27:24 +0000805 return cmpNumbers(GlobalNumbers->getNumber(L), GlobalNumbers->getNumber(R));
Stepan Dyatkovskiyd1031302014-05-07 09:05:10 +0000806}
807
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000808/// cmpType - compares two types,
809/// defines total ordering among the types set.
810/// See method declaration comments for more details.
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000811int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000812 PointerType *PTyL = dyn_cast<PointerType>(TyL);
813 PointerType *PTyR = dyn_cast<PointerType>(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000814
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000815 const DataLayout &DL = FnL->getParent()->getDataLayout();
816 if (PTyL && PTyL->getAddressSpace() == 0)
817 TyL = DL.getIntPtrType(TyL);
818 if (PTyR && PTyR->getAddressSpace() == 0)
819 TyR = DL.getIntPtrType(TyR);
Stepan Dyatkovskiyabb85052013-11-26 16:11:03 +0000820
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000821 if (TyL == TyR)
822 return 0;
Matt Arsenault5bcefab2013-11-10 01:44:37 +0000823
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000824 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID()))
825 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000826
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000827 switch (TyL->getTypeID()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000828 default:
829 llvm_unreachable("Unknown type!");
Duncan Sands408bb192010-07-07 07:48:00 +0000830 // Fall through in Release mode.
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000831 LLVM_FALLTHROUGH;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000832 case Type::IntegerTyID:
JF Bastien057292a2015-08-21 23:27:24 +0000833 return cmpNumbers(cast<IntegerType>(TyL)->getBitWidth(),
834 cast<IntegerType>(TyR)->getBitWidth());
835 case Type::VectorTyID: {
836 VectorType *VTyL = cast<VectorType>(TyL), *VTyR = cast<VectorType>(TyR);
837 if (int Res = cmpNumbers(VTyL->getNumElements(), VTyR->getNumElements()))
838 return Res;
839 return cmpTypes(VTyL->getElementType(), VTyR->getElementType());
840 }
841 // TyL == TyR would have returned true earlier, because types are uniqued.
Nick Lewyckye04dc222009-06-12 08:04:51 +0000842 case Type::VoidTyID:
843 case Type::FloatTyID:
844 case Type::DoubleTyID:
845 case Type::X86_FP80TyID:
846 case Type::FP128TyID:
847 case Type::PPC_FP128TyID:
848 case Type::LabelTyID:
849 case Type::MetadataTyID:
David Majnemerb611e3f2015-08-14 05:09:07 +0000850 case Type::TokenTyID:
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000851 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000852
Nick Lewyckye04dc222009-06-12 08:04:51 +0000853 case Type::PointerTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000854 assert(PTyL && PTyR && "Both types must be pointers here.");
855 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000856 }
857
858 case Type::StructTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000859 StructType *STyL = cast<StructType>(TyL);
860 StructType *STyR = cast<StructType>(TyR);
861 if (STyL->getNumElements() != STyR->getNumElements())
862 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000863
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000864 if (STyL->isPacked() != STyR->isPacked())
865 return cmpNumbers(STyL->isPacked(), STyR->isPacked());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000866
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000867 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) {
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000868 if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000869 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000870 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000871 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000872 }
873
874 case Type::FunctionTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000875 FunctionType *FTyL = cast<FunctionType>(TyL);
876 FunctionType *FTyR = cast<FunctionType>(TyR);
877 if (FTyL->getNumParams() != FTyR->getNumParams())
878 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams());
Nick Lewyckye04dc222009-06-12 08:04:51 +0000879
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000880 if (FTyL->isVarArg() != FTyR->isVarArg())
881 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg());
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000882
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000883 if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType()))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000884 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000885
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000886 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) {
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000887 if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i)))
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000888 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000889 }
Stepan Dyatkovskiyd8eb0bc2014-03-13 11:54:50 +0000890 return 0;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000891 }
892
Nick Lewycky375efe32010-07-16 06:31:12 +0000893 case Type::ArrayTyID: {
Stepan Dyatkovskiya53cf972014-03-14 08:48:52 +0000894 ArrayType *ATyL = cast<ArrayType>(TyL);
895 ArrayType *ATyR = cast<ArrayType>(TyR);
896 if (ATyL->getNumElements() != ATyR->getNumElements())
897 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements());
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000898 return cmpTypes(ATyL->getElementType(), ATyR->getElementType());
Nick Lewycky375efe32010-07-16 06:31:12 +0000899 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000900 }
901}
902
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000903// Determine whether the two operations are the same except that pointer-to-A
904// and pointer-to-B are equivalent. This should be kept in sync with
905// Instruction::isSameOperationAs.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000906// Read method declaration comments for more details.
Stepan Dyatkovskiy87c046182014-07-31 07:16:59 +0000907int FunctionComparator::cmpOperations(const Instruction *L,
908 const Instruction *R) const {
Nick Lewyckycb1a4c22011-02-06 05:04:00 +0000909 // Differences from Instruction::isSameOperationAs:
JF Bastien1bb32ac2016-04-12 21:13:01 +0000910 // * replace type comparison with calls to cmpTypes.
911 // * we test for I->getRawSubclassOptionalData (nuw/nsw/tail) at the top.
912 // * because of the above, we don't test for the tail bit on calls later on.
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000913 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode()))
914 return Res;
915
916 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands()))
917 return Res;
918
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000919 if (int Res = cmpTypes(L->getType(), R->getType()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000920 return Res;
921
922 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(),
923 R->getRawSubclassOptionalData()))
924 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000925
926 // We have two instructions of identical opcode and #operands. Check to see
927 // if all operands are the same type
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000928 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) {
929 if (int Res =
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +0000930 cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000931 return Res;
932 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000933
934 // Check special state that is a part of some instructions.
JF Bastien4f43cfd2016-04-12 00:03:26 +0000935 if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) {
936 if (int Res = cmpTypes(AI->getAllocatedType(),
937 cast<AllocaInst>(R)->getAllocatedType()))
938 return Res;
939 return cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment());
940 }
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000941 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) {
942 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile()))
943 return Res;
944 if (int Res =
945 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment()))
946 return Res;
947 if (int Res =
JF Bastien800f87a2016-04-06 21:19:33 +0000948 cmpOrderings(LI->getOrdering(), cast<LoadInst>(R)->getOrdering()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000949 return Res;
Stepan Dyatkovskiy6baeb882014-06-20 19:11:56 +0000950 if (int Res =
951 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope()))
952 return Res;
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000953 return cmpRangeMetadata(LI->getMetadata(LLVMContext::MD_range),
954 cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000955 }
956 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) {
957 if (int Res =
958 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile()))
959 return Res;
960 if (int Res =
961 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment()))
962 return Res;
963 if (int Res =
JF Bastien800f87a2016-04-06 21:19:33 +0000964 cmpOrderings(SI->getOrdering(), cast<StoreInst>(R)->getOrdering()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000965 return Res;
966 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope());
967 }
968 if (const CmpInst *CI = dyn_cast<CmpInst>(L))
969 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate());
970 if (const CallInst *CI = dyn_cast<CallInst>(L)) {
971 if (int Res = cmpNumbers(CI->getCallingConv(),
972 cast<CallInst>(R)->getCallingConv()))
973 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000974 if (int Res =
975 cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes()))
976 return Res;
Sanjoy Das2a74eb02015-12-14 19:11:40 +0000977 if (int Res = cmpOperandBundlesSchema(CI, R))
978 return Res;
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000979 return cmpRangeMetadata(
980 CI->getMetadata(LLVMContext::MD_range),
981 cast<CallInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000982 }
Sanjoy Dasadfec012015-12-14 19:11:45 +0000983 if (const InvokeInst *II = dyn_cast<InvokeInst>(L)) {
984 if (int Res = cmpNumbers(II->getCallingConv(),
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000985 cast<InvokeInst>(R)->getCallingConv()))
986 return Res;
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000987 if (int Res =
Sanjoy Dasadfec012015-12-14 19:11:45 +0000988 cmpAttrs(II->getAttributes(), cast<InvokeInst>(R)->getAttributes()))
Stepan Dyatkovskiydee612d2014-07-15 10:46:51 +0000989 return Res;
Sanjoy Dasadfec012015-12-14 19:11:45 +0000990 if (int Res = cmpOperandBundlesSchema(II, R))
Sanjoy Das2a74eb02015-12-14 19:11:40 +0000991 return Res;
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000992 return cmpRangeMetadata(
Sanjoy Dasadfec012015-12-14 19:11:45 +0000993 II->getMetadata(LLVMContext::MD_range),
JF Bastienf5aa1ca2015-08-28 16:49:09 +0000994 cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range));
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +0000995 }
996 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) {
997 ArrayRef<unsigned> LIndices = IVI->getIndices();
998 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices();
999 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
1000 return Res;
1001 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
1002 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
1003 return Res;
1004 }
JF Bastienf90029b2016-04-12 21:23:05 +00001005 return 0;
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +00001006 }
1007 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) {
1008 ArrayRef<unsigned> LIndices = EVI->getIndices();
1009 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices();
1010 if (int Res = cmpNumbers(LIndices.size(), RIndices.size()))
1011 return Res;
1012 for (size_t i = 0, e = LIndices.size(); i != e; ++i) {
1013 if (int Res = cmpNumbers(LIndices[i], RIndices[i]))
1014 return Res;
1015 }
1016 }
1017 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) {
1018 if (int Res =
JF Bastien800f87a2016-04-06 21:19:33 +00001019 cmpOrderings(FI->getOrdering(), cast<FenceInst>(R)->getOrdering()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +00001020 return Res;
1021 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope());
1022 }
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +00001023 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) {
1024 if (int Res = cmpNumbers(CXI->isVolatile(),
1025 cast<AtomicCmpXchgInst>(R)->isVolatile()))
1026 return Res;
Tim Northover420a2162014-06-13 14:24:07 +00001027 if (int Res = cmpNumbers(CXI->isWeak(),
1028 cast<AtomicCmpXchgInst>(R)->isWeak()))
1029 return Res;
JF Bastien800f87a2016-04-06 21:19:33 +00001030 if (int Res =
1031 cmpOrderings(CXI->getSuccessOrdering(),
1032 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +00001033 return Res;
JF Bastien800f87a2016-04-06 21:19:33 +00001034 if (int Res =
1035 cmpOrderings(CXI->getFailureOrdering(),
1036 cast<AtomicCmpXchgInst>(R)->getFailureOrdering()))
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +00001037 return Res;
1038 return cmpNumbers(CXI->getSynchScope(),
1039 cast<AtomicCmpXchgInst>(R)->getSynchScope());
1040 }
1041 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) {
1042 if (int Res = cmpNumbers(RMWI->getOperation(),
1043 cast<AtomicRMWInst>(R)->getOperation()))
1044 return Res;
1045 if (int Res = cmpNumbers(RMWI->isVolatile(),
1046 cast<AtomicRMWInst>(R)->isVolatile()))
1047 return Res;
JF Bastien800f87a2016-04-06 21:19:33 +00001048 if (int Res = cmpOrderings(RMWI->getOrdering(),
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +00001049 cast<AtomicRMWInst>(R)->getOrdering()))
1050 return Res;
1051 return cmpNumbers(RMWI->getSynchScope(),
1052 cast<AtomicRMWInst>(R)->getSynchScope());
1053 }
Mark Lacey9b5fcf62016-05-20 18:39:11 +00001054 if (const PHINode *PNL = dyn_cast<PHINode>(L)) {
1055 const PHINode *PNR = cast<PHINode>(R);
1056 // Ensure that in addition to the incoming values being identical
1057 // (checked by the caller of this function), the incoming blocks
1058 // are also identical.
1059 for (unsigned i = 0, e = PNL->getNumIncomingValues(); i != e; ++i) {
1060 if (int Res =
1061 cmpValues(PNL->getIncomingBlock(i), PNR->getIncomingBlock(i)))
1062 return Res;
1063 }
1064 }
Stepan Dyatkovskiyfa6820a2014-05-16 11:02:22 +00001065 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001066}
1067
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001068// Determine whether two GEP operations perform the same underlying arithmetic.
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001069// Read method declaration comments for more details.
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +00001070int FunctionComparator::cmpGEPs(const GEPOperator *GEPL,
JF Bastien83314582016-04-13 21:12:21 +00001071 const GEPOperator *GEPR) const {
Matt Arsenault5bcefab2013-11-10 01:44:37 +00001072
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001073 unsigned int ASL = GEPL->getPointerAddressSpace();
1074 unsigned int ASR = GEPR->getPointerAddressSpace();
1075
1076 if (int Res = cmpNumbers(ASL, ASR))
1077 return Res;
1078
1079 // When we have target data, we can reduce the GEP down to the value in bytes
1080 // added to the address.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001081 const DataLayout &DL = FnL->getParent()->getDataLayout();
1082 unsigned BitWidth = DL.getPointerSizeInBits(ASL);
1083 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0);
1084 if (GEPL->accumulateConstantOffset(DL, OffsetL) &&
1085 GEPR->accumulateConstantOffset(DL, OffsetR))
1086 return cmpAPInts(OffsetL, OffsetR);
JF Bastien26aca142015-09-14 15:37:48 +00001087 if (int Res = cmpTypes(GEPL->getSourceElementType(),
1088 GEPR->getSourceElementType()))
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001089 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001090
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001091 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands()))
1092 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001093
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001094 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) {
1095 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i)))
1096 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001097 }
1098
Stepan Dyatkovskiy948366a2014-05-16 11:55:02 +00001099 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001100}
1101
JF Bastien057292a2015-08-21 23:27:24 +00001102int FunctionComparator::cmpInlineAsm(const InlineAsm *L,
1103 const InlineAsm *R) const {
1104 // InlineAsm's are uniqued. If they are the same pointer, obviously they are
1105 // the same, otherwise compare the fields.
1106 if (L == R)
1107 return 0;
1108 if (int Res = cmpTypes(L->getFunctionType(), R->getFunctionType()))
1109 return Res;
1110 if (int Res = cmpMem(L->getAsmString(), R->getAsmString()))
1111 return Res;
1112 if (int Res = cmpMem(L->getConstraintString(), R->getConstraintString()))
1113 return Res;
1114 if (int Res = cmpNumbers(L->hasSideEffects(), R->hasSideEffects()))
1115 return Res;
1116 if (int Res = cmpNumbers(L->isAlignStack(), R->isAlignStack()))
1117 return Res;
1118 if (int Res = cmpNumbers(L->getDialect(), R->getDialect()))
1119 return Res;
1120 llvm_unreachable("InlineAsm blocks were not uniqued.");
1121 return 0;
1122}
1123
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001124/// Compare two values used by the two functions under pair-wise comparison. If
1125/// this is the first time the values are seen, they're added to the mapping so
1126/// that we will detect mismatches on next use.
1127/// See comments in declaration for more details.
JF Bastien83314582016-04-13 21:12:21 +00001128int FunctionComparator::cmpValues(const Value *L, const Value *R) const {
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001129 // Catch self-reference case.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001130 if (L == FnL) {
1131 if (R == FnR)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001132 return 0;
1133 return -1;
1134 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001135 if (R == FnR) {
1136 if (L == FnL)
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001137 return 0;
1138 return 1;
Nick Lewycky13e04ae2011-01-27 08:38:19 +00001139 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001140
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001141 const Constant *ConstL = dyn_cast<Constant>(L);
1142 const Constant *ConstR = dyn_cast<Constant>(R);
1143 if (ConstL && ConstR) {
1144 if (L == R)
1145 return 0;
1146 return cmpConstants(ConstL, ConstR);
1147 }
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001148
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001149 if (ConstL)
1150 return 1;
1151 if (ConstR)
1152 return -1;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001153
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001154 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L);
1155 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R);
1156
1157 if (InlineAsmL && InlineAsmR)
JF Bastien057292a2015-08-21 23:27:24 +00001158 return cmpInlineAsm(InlineAsmL, InlineAsmR);
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001159 if (InlineAsmL)
1160 return 1;
1161 if (InlineAsmR)
1162 return -1;
1163
1164 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())),
1165 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size()));
1166
1167 return cmpNumbers(LeftSN.first->second, RightSN.first->second);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001168}
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001169// Test whether two basic blocks have equivalent behaviour.
JF Bastien057292a2015-08-21 23:27:24 +00001170int FunctionComparator::cmpBasicBlocks(const BasicBlock *BBL,
JF Bastien83314582016-04-13 21:12:21 +00001171 const BasicBlock *BBR) const {
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001172 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end();
1173 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end();
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001174
1175 do {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001176 if (int Res = cmpValues(&*InstL, &*InstR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001177 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001178
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001179 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL);
1180 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR);
Nick Lewycky47b71c52009-06-13 19:09:52 +00001181
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001182 if (GEPL && !GEPR)
1183 return 1;
1184 if (GEPR && !GEPL)
1185 return -1;
Nick Lewycky47b71c52009-06-13 19:09:52 +00001186
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001187 if (GEPL && GEPR) {
1188 if (int Res =
1189 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand()))
1190 return Res;
Stepan Dyatkovskiy016dadd2014-08-25 08:12:45 +00001191 if (int Res = cmpGEPs(GEPL, GEPR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001192 return Res;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001193 } else {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001194 if (int Res = cmpOperations(&*InstL, &*InstR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001195 return Res;
1196 assert(InstL->getNumOperands() == InstR->getNumOperands());
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001197
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001198 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) {
1199 Value *OpL = InstL->getOperand(i);
1200 Value *OpR = InstR->getOperand(i);
1201 if (int Res = cmpValues(OpL, OpR))
1202 return Res;
JF Bastien9dc042a2015-08-26 03:02:58 +00001203 // cmpValues should ensure this is true.
1204 assert(cmpTypes(OpL->getType(), OpR->getType()) == 0);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001205 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001206 }
1207
Richard Trieu7a083812016-02-18 22:09:30 +00001208 ++InstL;
1209 ++InstR;
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001210 } while (InstL != InstLE && InstR != InstRE);
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001211
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001212 if (InstL != InstLE && InstR == InstRE)
1213 return 1;
1214 if (InstL == InstLE && InstR != InstRE)
1215 return -1;
1216 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001217}
1218
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001219// Test whether the two functions have equivalent behaviour.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001220int FunctionComparator::compare() {
Stepan Dyatkovskiycfd641f2014-05-07 11:11:39 +00001221 sn_mapL.clear();
1222 sn_mapR.clear();
1223
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001224 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes()))
1225 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001226
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001227 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC()))
1228 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001229
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001230 if (FnL->hasGC()) {
JF Bastien057292a2015-08-21 23:27:24 +00001231 if (int Res = cmpMem(FnL->getGC(), FnR->getGC()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001232 return Res;
1233 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001234
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001235 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection()))
1236 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001237
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001238 if (FnL->hasSection()) {
JF Bastien057292a2015-08-21 23:27:24 +00001239 if (int Res = cmpMem(FnL->getSection(), FnR->getSection()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001240 return Res;
1241 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001242
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001243 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg()))
1244 return Res;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001245
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001246 // TODO: if it's internal and only used in direct calls, we could handle this
1247 // case too.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001248 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv()))
1249 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001250
Stepan Dyatkovskiy0b765de2014-08-25 08:16:39 +00001251 if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType()))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001252 return Res;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001253
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001254 assert(FnL->arg_size() == FnR->arg_size() &&
Nick Lewycky71972d42010-09-07 01:42:10 +00001255 "Identically typed functions have different numbers of args!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001256
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001257 // Visit the arguments so that they get enumerated in the order they're
1258 // passed in.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001259 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(),
1260 ArgRI = FnR->arg_begin(),
1261 ArgLE = FnL->arg_end();
1262 ArgLI != ArgLE; ++ArgLI, ++ArgRI) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001263 if (cmpValues(&*ArgLI, &*ArgRI) != 0)
Nick Lewycky71972d42010-09-07 01:42:10 +00001264 llvm_unreachable("Arguments repeat!");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001265 }
1266
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001267 // We do a CFG-ordered walk since the actual ordering of the blocks in the
1268 // linked list is immaterial. Our walk starts at the entry block for both
Nick Lewyckyf52bd9c2010-08-02 05:23:03 +00001269 // functions, then takes each block from each terminator in order. As an
1270 // artifact, this also means that unreachable blocks are ignored.
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001271 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs;
Matthias Braunb30f2f512016-01-30 01:24:31 +00001272 SmallPtrSet<const BasicBlock *, 32> VisitedBBs; // in terms of F1.
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001273
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001274 FnLBBs.push_back(&FnL->getEntryBlock());
1275 FnRBBs.push_back(&FnR->getEntryBlock());
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001276
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001277 VisitedBBs.insert(FnLBBs[0]);
1278 while (!FnLBBs.empty()) {
1279 const BasicBlock *BBL = FnLBBs.pop_back_val();
1280 const BasicBlock *BBR = FnRBBs.pop_back_val();
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001281
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001282 if (int Res = cmpValues(BBL, BBR))
1283 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001284
JF Bastien057292a2015-08-21 23:27:24 +00001285 if (int Res = cmpBasicBlocks(BBL, BBR))
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001286 return Res;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001287
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001288 const TerminatorInst *TermL = BBL->getTerminator();
1289 const TerminatorInst *TermR = BBR->getTerminator();
1290
1291 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors());
1292 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) {
David Blaikie70573dc2014-11-19 07:49:26 +00001293 if (!VisitedBBs.insert(TermL->getSuccessor(i)).second)
Nick Lewycky2b3cbac2010-05-13 06:45:13 +00001294 continue;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001295
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001296 FnLBBs.push_back(TermL->getSuccessor(i));
1297 FnRBBs.push_back(TermR->getSuccessor(i));
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001298 }
1299 }
Stepan Dyatkovskiy17ee5ac2014-06-21 17:55:51 +00001300 return 0;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001301}
1302
Benjamin Kramer83709b12015-11-16 09:01:28 +00001303namespace {
JF Bastien5e4303d2015-08-15 01:18:18 +00001304// Accumulate the hash of a sequence of 64-bit integers. This is similar to a
1305// hash of a sequence of 64bit ints, but the entire input does not need to be
1306// available at once. This interface is necessary for functionHash because it
1307// needs to accumulate the hash as the structure of the function is traversed
1308// without saving these values to an intermediate buffer. This form of hashing
1309// is not often needed, as usually the object to hash is just read from a
1310// buffer.
1311class HashAccumulator64 {
1312 uint64_t Hash;
1313public:
1314 // Initialize to random constant, so the state isn't zero.
1315 HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; }
1316 void add(uint64_t V) {
1317 Hash = llvm::hashing::detail::hash_16_bytes(Hash, V);
1318 }
1319 // No finishing is required, because the entire hash value is used.
1320 uint64_t getHash() { return Hash; }
1321};
Benjamin Kramer83709b12015-11-16 09:01:28 +00001322} // end anonymous namespace
JF Bastien5e4303d2015-08-15 01:18:18 +00001323
1324// A function hash is calculated by considering only the number of arguments and
1325// whether a function is varargs, the order of basic blocks (given by the
1326// successors of each basic block in depth first order), and the order of
1327// opcodes of each instruction within each of these basic blocks. This mirrors
1328// the strategy compare() uses to compare functions by walking the BBs in depth
1329// first order and comparing each instruction in sequence. Because this hash
1330// does not look at the operands, it is insensitive to things such as the
1331// target of calls and the constants used in the function, which makes it useful
1332// when possibly merging functions which are the same modulo constants and call
1333// targets.
1334FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) {
1335 HashAccumulator64 H;
1336 H.add(F.isVarArg());
1337 H.add(F.arg_size());
1338
1339 SmallVector<const BasicBlock *, 8> BBs;
1340 SmallSet<const BasicBlock *, 16> VisitedBBs;
1341
JF Bastien057292a2015-08-21 23:27:24 +00001342 // Walk the blocks in the same order as FunctionComparator::cmpBasicBlocks(),
JF Bastien5e4303d2015-08-15 01:18:18 +00001343 // accumulating the hash of the function "structure." (BB and opcode sequence)
1344 BBs.push_back(&F.getEntryBlock());
1345 VisitedBBs.insert(BBs[0]);
1346 while (!BBs.empty()) {
1347 const BasicBlock *BB = BBs.pop_back_val();
1348 // This random value acts as a block header, as otherwise the partition of
1349 // opcodes into BBs wouldn't affect the hash, only the order of the opcodes
1350 H.add(45798);
1351 for (auto &Inst : *BB) {
1352 H.add(Inst.getOpcode());
1353 }
1354 const TerminatorInst *Term = BB->getTerminator();
1355 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
1356 if (!VisitedBBs.insert(Term->getSuccessor(i)).second)
1357 continue;
1358 BBs.push_back(Term->getSuccessor(i));
1359 }
1360 }
1361 return H.getHash();
1362}
1363
1364
Nick Lewycky564fcca2011-01-28 07:36:21 +00001365namespace {
1366
1367/// MergeFunctions finds functions which will generate identical machine code,
1368/// by considering all pointer types to be equivalent. Once identified,
1369/// MergeFunctions will fold them by replacing a call to one to a call to a
1370/// bitcast of the other.
1371///
1372class MergeFunctions : public ModulePass {
1373public:
1374 static char ID;
1375 MergeFunctions()
JF Bastien3a4ad612015-09-02 23:55:23 +00001376 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)), FNodesInTree(),
JF Bastien057292a2015-08-21 23:27:24 +00001377 HasGlobalAliases(false) {
Nick Lewycky564fcca2011-01-28 07:36:21 +00001378 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
1379 }
1380
Craig Topper3e4c6972014-03-05 09:10:37 +00001381 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001382
1383private:
JF Bastien057292a2015-08-21 23:27:24 +00001384 // The function comparison operator is provided here so that FunctionNodes do
1385 // not need to become larger with another pointer.
1386 class FunctionNodeCmp {
1387 GlobalNumberState* GlobalNumbers;
1388 public:
1389 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
1390 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
1391 // Order first by hashes, then full function comparison.
1392 if (LHS.getHash() != RHS.getHash())
1393 return LHS.getHash() < RHS.getHash();
1394 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
1395 return FCmp.compare() == -1;
1396 }
1397 };
1398 typedef std::set<FunctionNode, FunctionNodeCmp> FnTreeType;
1399
1400 GlobalNumberState GlobalNumbers;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001401
1402 /// A work queue of functions that may have been modified and should be
1403 /// analyzed again.
1404 std::vector<WeakVH> Deferred;
1405
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001406 /// Checks the rules of order relation introduced among functions set.
1407 /// Returns true, if sanity check has been passed, and false if failed.
1408 bool doSanityCheck(std::vector<WeakVH> &Worklist);
1409
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001410 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +00001411 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001412 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001413
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001414 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +00001415 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001416 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001417
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001418 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +00001419 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001420 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001421
1422 /// Replace all direct calls of Old with calls of New. Will bitcast New if
1423 /// necessary to make types match.
1424 void replaceDirectCallers(Function *Old, Function *New);
1425
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001426 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
1427 /// be converted into a thunk. In either case, it should never be visited
1428 /// again.
1429 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001430
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001431 /// Replace G with a thunk or an alias to F. Deletes G.
1432 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001433
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001434 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1435 /// of G with bitcast(F). Deletes G.
1436 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001437
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001438 /// Replace G with an alias to F. Deletes G.
1439 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001440
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001441 /// Replace function F with function G in the function tree.
JF Bastien3a4ad612015-09-02 23:55:23 +00001442 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001443
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001444 /// The set of all distinct functions. Use the insert() and remove() methods
JF Bastien3a4ad612015-09-02 23:55:23 +00001445 /// to modify it. The map allows efficient lookup and deferring of Functions.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001446 FnTreeType FnTree;
JF Bastien3a4ad612015-09-02 23:55:23 +00001447 // Map functions to the iterators of the FunctionNode which contains them
1448 // in the FnTree. This must be updated carefully whenever the FnTree is
1449 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
1450 // dangling iterators into FnTree. The invariant that preserves this is that
1451 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
1452 ValueMap<Function*, FnTreeType::iterator> FNodesInTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001453
Nick Lewycky564fcca2011-01-28 07:36:21 +00001454 /// Whether or not the target supports global aliases.
1455 bool HasGlobalAliases;
1456};
1457
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001458} // end anonymous namespace
Nick Lewycky564fcca2011-01-28 07:36:21 +00001459
1460char MergeFunctions::ID = 0;
1461INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
1462
1463ModulePass *llvm::createMergeFunctionsPass() {
1464 return new MergeFunctions();
1465}
1466
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001467bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
1468 if (const unsigned Max = NumFunctionsForSanityCheck) {
1469 unsigned TripleNumber = 0;
1470 bool Valid = true;
1471
1472 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
1473
1474 unsigned i = 0;
1475 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
1476 I != E && i < Max; ++I, ++i) {
1477 unsigned j = i;
1478 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
1479 Function *F1 = cast<Function>(*I);
1480 Function *F2 = cast<Function>(*J);
JF Bastien057292a2015-08-21 23:27:24 +00001481 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
1482 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001483
1484 // If F1 <= F2, then F2 >= F1, otherwise report failure.
1485 if (Res1 != -Res2) {
1486 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
1487 << "\n";
1488 F1->dump();
1489 F2->dump();
1490 Valid = false;
1491 }
1492
1493 if (Res1 == 0)
1494 continue;
1495
1496 unsigned k = j;
1497 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
1498 ++k, ++K, ++TripleNumber) {
1499 if (K == J)
1500 continue;
1501
1502 Function *F3 = cast<Function>(*K);
JF Bastien057292a2015-08-21 23:27:24 +00001503 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
1504 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001505
1506 bool Transitive = true;
1507
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001508 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001509 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001510 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001511 } else if (Res3 != 0 && Res3 == -Res4) {
1512 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001513 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +00001514 } else if (Res4 != 0 && -Res3 == Res4) {
1515 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001516 Transitive = Res4 == -Res1;
1517 }
1518
1519 if (!Transitive) {
1520 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
1521 << TripleNumber << "\n";
1522 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
1523 << Res4 << "\n";
1524 F1->dump();
1525 F2->dump();
1526 F3->dump();
1527 Valid = false;
1528 }
1529 }
1530 }
1531 }
1532
1533 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
1534 return Valid;
1535 }
1536 return true;
1537}
1538
Nick Lewycky564fcca2011-01-28 07:36:21 +00001539bool MergeFunctions::runOnModule(Module &M) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001540 if (skipModule(M))
1541 return false;
1542
Nick Lewycky564fcca2011-01-28 07:36:21 +00001543 bool Changed = false;
Nick Lewycky564fcca2011-01-28 07:36:21 +00001544
JF Bastien5e4303d2015-08-15 01:18:18 +00001545 // All functions in the module, ordered by hash. Functions with a unique
1546 // hash value are easily eliminated.
1547 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
1548 HashedFuncs;
1549 for (Function &Func : M) {
1550 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
1551 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
1552 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001553 }
Nick Lewycky564fcca2011-01-28 07:36:21 +00001554
NAKAMURA Takumi51962752015-08-16 02:41:23 +00001555 std::stable_sort(
1556 HashedFuncs.begin(), HashedFuncs.end(),
1557 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
1558 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
1559 return a.first < b.first;
1560 });
JF Bastien5e4303d2015-08-15 01:18:18 +00001561
1562 auto S = HashedFuncs.begin();
1563 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
1564 // If the hash value matches the previous value or the next one, we must
1565 // consider merging it. Otherwise it is dropped and never considered again.
1566 if ((I != S && std::prev(I)->first == I->first) ||
1567 (std::next(I) != IE && std::next(I)->first == I->first) ) {
1568 Deferred.push_back(WeakVH(I->second));
1569 }
1570 }
1571
Nick Lewycky564fcca2011-01-28 07:36:21 +00001572 do {
1573 std::vector<WeakVH> Worklist;
1574 Deferred.swap(Worklist);
1575
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +00001576 DEBUG(doSanityCheck(Worklist));
1577
Nick Lewycky564fcca2011-01-28 07:36:21 +00001578 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
1579 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
1580
Erik Eckstein0c48dd82016-05-31 17:20:23 +00001581 // Insert functions and merge them.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001582 for (WeakVH &I : Worklist) {
1583 if (!I)
1584 continue;
1585 Function *F = cast<Function>(I);
Erik Eckstein0c48dd82016-05-31 17:20:23 +00001586 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001587 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +00001588 }
1589 }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001590 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +00001591 } while (!Deferred.empty());
1592
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001593 FnTree.clear();
Arnold Schwaighofer0591c5d2015-10-05 17:26:36 +00001594 GlobalNumbers.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +00001595
1596 return Changed;
1597}
1598
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001599// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001600void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
1601 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001602 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
1603 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001604 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001605 CallSite CS(U->getUser());
1606 if (CS && CS.isCallee(U)) {
Arnold Schwaighofer36512332015-07-21 17:07:07 +00001607 // Transfer the called function's attributes to the call site. Due to the
JF Bastienfa946232015-09-10 18:08:35 +00001608 // bitcast we will 'lose' ABI changing attributes because the 'called
Arnold Schwaighofer36512332015-07-21 17:07:07 +00001609 // function' is no longer a Function* but the bitcast. Code that looks up
1610 // the attributes from the called function will fail.
JF Bastienfa946232015-09-10 18:08:35 +00001611
1612 // FIXME: This is not actually true, at least not anymore. The callsite
1613 // will always have the same ABI affecting attributes as the callee,
1614 // because otherwise the original input has UB. Note that Old and New
1615 // always have matching ABI, so no attributes need to be changed.
1616 // Transferring other attributes may help other optimizations, but that
1617 // should be done uniformly and not in this ad-hoc way.
Arnold Schwaighofer36512332015-07-21 17:07:07 +00001618 auto &Context = New->getContext();
1619 auto NewFuncAttrs = New->getAttributes();
1620 auto CallSiteAttrs = CS.getAttributes();
1621
1622 CallSiteAttrs = CallSiteAttrs.addAttributes(
1623 Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes());
1624
1625 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) {
1626 AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx);
1627 if (Attrs.getNumSlots())
1628 CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs);
1629 }
1630
1631 CS.setAttributes(CallSiteAttrs);
1632
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001633 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001634 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001635 }
1636 }
1637}
1638
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001639// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
1640void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001641 if (HasGlobalAliases && G->hasGlobalUnnamedAddr()) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001642 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
1643 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001644 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001645 return;
1646 }
1647 }
1648
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001649 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001650}
1651
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001652// Helper for writeThunk,
1653// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +00001654// but a bit simpler then CastInst::getCastOpcode.
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001655static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001656 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +00001657 if (SrcTy->isStructTy()) {
1658 assert(DestTy->isStructTy());
1659 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
1660 Value *Result = UndefValue::get(DestTy);
1661 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
1662 Value *Element = createCast(
Craig Toppere1d12942014-08-27 05:25:25 +00001663 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
Carlo Kok307625c2014-04-30 17:53:04 +00001664 DestTy->getStructElementType(I));
1665
1666 Result =
Craig Toppere1d12942014-08-27 05:25:25 +00001667 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
Carlo Kok307625c2014-04-30 17:53:04 +00001668 }
1669 return Result;
1670 }
1671 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001672 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
1673 return Builder.CreateIntToPtr(V, DestTy);
1674 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
1675 return Builder.CreatePtrToInt(V, DestTy);
1676 else
1677 return Builder.CreateBitCast(V, DestTy);
1678}
1679
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001680// Replace G with a simple tail call to bitcast(F). Also replace direct uses
1681// of G with bitcast(F). Deletes G.
1682void MergeFunctions::writeThunk(Function *F, Function *G) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001683 if (!G->isInterposable()) {
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001684 // Redirect direct callers of G to F.
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001685 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001686 }
1687
Nick Lewycky71972d42010-09-07 01:42:10 +00001688 // If G was internal then we may have replaced all uses of G with F. If so,
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001689 // stop here and delete G. There's no need for a thunk.
1690 if (G->hasLocalLinkage() && G->use_empty()) {
1691 G->eraseFromParent();
1692 return;
1693 }
1694
Nick Lewycky25675ac2009-06-12 15:56:56 +00001695 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
1696 G->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +00001697 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG);
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001698 IRBuilder<> Builder(BB);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001699
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001700 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001701 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00001702 FunctionType *FFTy = F->getFunctionType();
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +00001703 for (Argument & AI : NewG->args()) {
1704 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001705 ++i;
1706 }
1707
Jay Foad5bd375a2011-07-15 08:37:34 +00001708 CallInst *CI = Builder.CreateCall(F, Args);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001709 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +00001710 CI->setCallingConv(F->getCallingConv());
JF Bastienfa946232015-09-10 18:08:35 +00001711 CI->setAttributes(F->getAttributes());
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001712 if (NewG->getReturnType()->isVoidTy()) {
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001713 Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +00001714 } else {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +00001715 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +00001716 }
1717
1718 NewG->copyAttributesFrom(G);
1719 NewG->takeName(G);
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001720 removeUsers(G);
Nick Lewyckye04dc222009-06-12 08:04:51 +00001721 G->replaceAllUsesWith(NewG);
1722 G->eraseFromParent();
Nick Lewycky71972d42010-09-07 01:42:10 +00001723
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001724 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +00001725 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +00001726}
1727
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001728// Replace G with an alias to F and delete G.
1729void MergeFunctions::writeAlias(Function *F, Function *G) {
David Blaikie6614d8d2015-09-14 20:29:26 +00001730 auto *GA = GlobalAlias::create(G->getLinkage(), "", F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001731 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
1732 GA->takeName(G);
1733 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001734 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001735 G->replaceAllUsesWith(GA);
1736 G->eraseFromParent();
1737
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001738 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001739 ++NumAliasesWritten;
1740}
1741
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001742// Merge two equivalent functions. Upon completion, Function G is deleted.
1743void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001744 if (F->isInterposable()) {
1745 assert(G->isInterposable());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +00001746
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001747 // Make them both thunks to the same internal function.
1748 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
1749 F->getParent());
1750 H->copyAttributesFrom(F);
1751 H->takeName(F);
1752 removeUsers(F);
1753 F->replaceAllUsesWith(H);
1754
1755 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
1756
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001757 if (HasGlobalAliases) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001758 writeAlias(F, G);
1759 writeAlias(F, H);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001760 } else {
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001761 writeThunk(F, G);
1762 writeThunk(F, H);
Nick Lewyckyf1cec162011-01-25 08:56:50 +00001763 }
Nick Lewycky71972d42010-09-07 01:42:10 +00001764
Arnold Schwaighofer7e226272015-06-09 18:19:17 +00001765 F->setAlignment(MaxAlignment);
1766 F->setLinkage(GlobalValue::PrivateLinkage);
Nick Lewycky71972d42010-09-07 01:42:10 +00001767 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +00001768 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001769 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +00001770 }
1771
Nick Lewyckye04dc222009-06-12 08:04:51 +00001772 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001773}
1774
JF Bastien3a4ad612015-09-02 23:55:23 +00001775/// Replace function F by function G.
1776void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001777 Function *G) {
JF Bastien3a4ad612015-09-02 23:55:23 +00001778 Function *F = FN.getFunc();
JF Bastien057292a2015-08-21 23:27:24 +00001779 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
1780 "The two functions must be equal");
JF Bastien3a4ad612015-09-02 23:55:23 +00001781
1782 auto I = FNodesInTree.find(F);
1783 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
1784 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
1785
1786 FnTreeType::iterator IterToFNInFnTree = I->second;
1787 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
1788 // Remove F -> FN and insert G -> FN
1789 FNodesInTree.erase(I);
1790 FNodesInTree.insert({G, IterToFNInFnTree});
1791 // Replace F with G in FN, which is stored inside the FnTree.
1792 FN.replaceBy(G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001793}
1794
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001795// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001796// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001797bool MergeFunctions::insert(Function *NewFunction) {
1798 std::pair<FnTreeType::iterator, bool> Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001799 FnTree.insert(FunctionNode(NewFunction));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001800
Nick Lewycky292e78c2011-02-09 06:32:02 +00001801 if (Result.second) {
JF Bastien3a4ad612015-09-02 23:55:23 +00001802 assert(FNodesInTree.count(NewFunction) == 0);
1803 FNodesInTree.insert({NewFunction, Result.first});
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001804 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001805 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +00001806 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001807
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +00001808 const FunctionNode &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +00001809
Matt Arsenault517d84e2013-10-01 18:05:30 +00001810 // Don't merge tiny functions, since it can just end up making the function
1811 // larger.
1812 // FIXME: Should still merge them if they are unnamed_addr and produce an
1813 // alias.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001814 if (NewFunction->size() == 1) {
1815 if (NewFunction->front().size() <= 2) {
1816 DEBUG(dbgs() << NewFunction->getName()
1817 << " is to small to bother merging\n");
Matt Arsenault517d84e2013-10-01 18:05:30 +00001818 return false;
1819 }
1820 }
1821
Arnold Schwaighofer0302da62015-06-09 00:03:29 +00001822 // Impose a total order (by name) on the replacement of functions. This is
1823 // important when operating on more than one module independently to prevent
1824 // cycles of thunks calling each other when the modules are linked together.
1825 //
Erik Eckstein0c48dd82016-05-31 17:20:23 +00001826 // First of all, we process strong functions before weak functions.
1827 if ((OldF.getFunc()->isInterposable() && !NewFunction->isInterposable()) ||
1828 (OldF.getFunc()->isInterposable() == NewFunction->isInterposable() &&
1829 OldF.getFunc()->getName() > NewFunction->getName())) {
1830 // Swap the two functions.
1831 Function *F = OldF.getFunc();
1832 replaceFunctionInTree(*Result.first, NewFunction);
1833 NewFunction = F;
1834 assert(OldF.getFunc() != F && "Must have swapped the functions.");
1835 }
Nick Lewycky00959372010-09-05 08:22:49 +00001836
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001837 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
1838 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +00001839
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001840 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001841 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +00001842 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +00001843}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +00001844
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +00001845// Remove a function from FnTree. If it was already in FnTree, add
1846// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001847void MergeFunctions::remove(Function *F) {
JF Bastien3a4ad612015-09-02 23:55:23 +00001848 auto I = FNodesInTree.find(F);
1849 if (I != FNodesInTree.end()) {
1850 DEBUG(dbgs() << "Deferred " << F->getName()<< ".\n");
1851 FnTree.erase(I->second);
1852 // I->second has been invalidated, remove it from the FNodesInTree map to
1853 // preserve the invariant.
1854 FNodesInTree.erase(I);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001855 Deferred.emplace_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001856 }
Nick Lewycky4e250c82011-01-02 02:46:33 +00001857}
Nick Lewycky00959372010-09-05 08:22:49 +00001858
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001859// For each instruction used by the value, remove() the function that contains
1860// the instruction. This should happen right before a call to RAUW.
1861void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +00001862 std::vector<Value *> Worklist;
1863 Worklist.push_back(V);
JF Bastien7289f732015-07-15 21:51:33 +00001864 SmallSet<Value*, 8> Visited;
1865 Visited.insert(V);
Nick Lewycky5361b842011-01-02 19:16:44 +00001866 while (!Worklist.empty()) {
1867 Value *V = Worklist.back();
1868 Worklist.pop_back();
1869
Chandler Carruthcdf47882014-03-09 03:16:01 +00001870 for (User *U : V->users()) {
1871 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +00001872 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +00001873 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +00001874 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +00001875 } else if (Constant *C = dyn_cast<Constant>(U)) {
JF Bastien7289f732015-07-15 21:51:33 +00001876 for (User *UU : C->users()) {
1877 if (!Visited.insert(UU).second)
1878 Worklist.push_back(UU);
1879 }
Nick Lewycky5361b842011-01-02 19:16:44 +00001880 }
Nick Lewycky00959372010-09-05 08:22:49 +00001881 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +00001882 }
Nick Lewycky00959372010-09-05 08:22:49 +00001883}