blob: a43b69f341301d3667f435b3ba13fb4f6f29fd40 [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"
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +000099#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000100#include "llvm/IR/IRBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000101#include "llvm/IR/Instructions.h"
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000102#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000103#include "llvm/IR/LLVMContext.h"
104#include "llvm/IR/Module.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"
Erik Eckstein4d6fb722016-11-11 21:15:13 +0000113#include "llvm/Transforms/Utils/FunctionComparator.h"
Nick Lewycky68984ed2010-08-31 08:29:37 +0000114#include <vector>
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000115
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000116using namespace llvm;
117
Chandler Carruth964daaa2014-04-22 02:55:47 +0000118#define DEBUG_TYPE "mergefunc"
119
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000120STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +0000121STATISTIC(NumThunksWritten, "Number of thunks generated");
122STATISTIC(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
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000131// Under option -mergefunc-preserve-debug-info we:
132// - Do not create a new function for a thunk.
133// - Retain the debug info for a thunk's parameters (and associated
134// instructions for the debug info) from the entry block.
135// Note: -debug will display the algorithm at work.
136// - Create debug-info for the call (to the shared implementation) made by
137// a thunk and its return value.
138// - Erase the rest of the function, retaining the (minimally sized) entry
139// block to create a thunk.
140// - Preserve a thunk's call site to point to the thunk even when both occur
141// within the same translation unit, to aid debugability. Note that this
142// behaviour differs from the underlying -mergefunc implementation which
143// modifies the thunk's call site to point to the shared implementation
144// when both occur within the same translation unit.
145static cl::opt<bool>
146 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
147 cl::init(false),
148 cl::desc("Preserve debug info in thunk when mergefunc "
149 "transformations are made."));
150
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000151namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000152
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000153class FunctionNode {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000154 mutable AssertingVH<Function> F;
JF Bastien5e4303d2015-08-15 01:18:18 +0000155 FunctionComparator::FunctionHash Hash;
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000156public:
JF Bastien5e4303d2015-08-15 01:18:18 +0000157 // Note the hash is recalculated potentially multiple times, but it is cheap.
JF Bastien057292a2015-08-21 23:27:24 +0000158 FunctionNode(Function *F)
159 : F(F), Hash(FunctionComparator::functionHash(*F)) {}
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000160 Function *getFunc() const { return F; }
JF Bastien057292a2015-08-21 23:27:24 +0000161 FunctionComparator::FunctionHash getHash() const { return Hash; }
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000162
163 /// Replace the reference to the function F by the function G, assuming their
164 /// implementations are equal.
165 void replaceBy(Function *G) const {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000166 F = G;
167 }
168
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000169 void release() { F = nullptr; }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000170};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000171
172/// MergeFunctions finds functions which will generate identical machine code,
173/// by considering all pointer types to be equivalent. Once identified,
174/// MergeFunctions will fold them by replacing a call to one to a call to a
175/// bitcast of the other.
176///
177class MergeFunctions : public ModulePass {
178public:
179 static char ID;
180 MergeFunctions()
whitequark9e8197a2017-07-27 19:36:13 +0000181 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)), FNodesInTree() {
Nick Lewycky564fcca2011-01-28 07:36:21 +0000182 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
183 }
184
Craig Topper3e4c6972014-03-05 09:10:37 +0000185 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000186
187private:
JF Bastien057292a2015-08-21 23:27:24 +0000188 // The function comparison operator is provided here so that FunctionNodes do
189 // not need to become larger with another pointer.
190 class FunctionNodeCmp {
191 GlobalNumberState* GlobalNumbers;
192 public:
193 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
194 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
195 // Order first by hashes, then full function comparison.
196 if (LHS.getHash() != RHS.getHash())
197 return LHS.getHash() < RHS.getHash();
198 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
199 return FCmp.compare() == -1;
200 }
201 };
202 typedef std::set<FunctionNode, FunctionNodeCmp> FnTreeType;
203
204 GlobalNumberState GlobalNumbers;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000205
206 /// A work queue of functions that may have been modified and should be
207 /// analyzed again.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000208 std::vector<WeakTrackingVH> Deferred;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000209
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000210 /// Checks the rules of order relation introduced among functions set.
211 /// Returns true, if sanity check has been passed, and false if failed.
Davide Italianob6681e22017-04-28 19:39:45 +0000212#ifndef NDEBUG
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000213 bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist);
Davide Italianob6681e22017-04-28 19:39:45 +0000214#endif
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000215
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000216 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +0000217 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000218 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000219
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000220 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +0000221 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000222 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000223
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000224 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +0000225 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000226 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000227
228 /// Replace all direct calls of Old with calls of New. Will bitcast New if
229 /// necessary to make types match.
230 void replaceDirectCallers(Function *Old, Function *New);
231
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000232 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
233 /// be converted into a thunk. In either case, it should never be visited
234 /// again.
235 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000236
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000237 /// Fill PDIUnrelatedWL with instructions from the entry block that are
238 /// unrelated to parameter related debug info.
239 void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
240 std::vector<Instruction *> &PDIUnrelatedWL);
241
242 /// Erase the rest of the CFG (i.e. barring the entry block).
243 void eraseTail(Function *G);
244
245 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
246 /// parameter debug info, from the entry block.
247 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
248
249 /// Replace G with a simple tail call to bitcast(F). Also (unless
250 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
251 /// delete G.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000252 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000253
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000254 /// Replace function F with function G in the function tree.
JF Bastien3a4ad612015-09-02 23:55:23 +0000255 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000256
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000257 /// The set of all distinct functions. Use the insert() and remove() methods
JF Bastien3a4ad612015-09-02 23:55:23 +0000258 /// to modify it. The map allows efficient lookup and deferring of Functions.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000259 FnTreeType FnTree;
JF Bastien3a4ad612015-09-02 23:55:23 +0000260 // Map functions to the iterators of the FunctionNode which contains them
261 // in the FnTree. This must be updated carefully whenever the FnTree is
262 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
263 // dangling iterators into FnTree. The invariant that preserves this is that
264 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
265 ValueMap<Function*, FnTreeType::iterator> FNodesInTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000266};
267
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000268} // end anonymous namespace
Nick Lewycky564fcca2011-01-28 07:36:21 +0000269
270char MergeFunctions::ID = 0;
271INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
272
273ModulePass *llvm::createMergeFunctionsPass() {
274 return new MergeFunctions();
275}
276
Davide Italianob6681e22017-04-28 19:39:45 +0000277#ifndef NDEBUG
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000278bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) {
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000279 if (const unsigned Max = NumFunctionsForSanityCheck) {
280 unsigned TripleNumber = 0;
281 bool Valid = true;
282
283 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
284
285 unsigned i = 0;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000286 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
287 E = Worklist.end();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000288 I != E && i < Max; ++I, ++i) {
289 unsigned j = i;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000290 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
291 ++J, ++j) {
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000292 Function *F1 = cast<Function>(*I);
293 Function *F2 = cast<Function>(*J);
JF Bastien057292a2015-08-21 23:27:24 +0000294 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
295 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000296
297 // If F1 <= F2, then F2 >= F1, otherwise report failure.
298 if (Res1 != -Res2) {
299 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
300 << "\n";
Matthias Braun194ded52017-01-28 06:53:55 +0000301 dbgs() << *F1 << '\n' << *F2 << '\n';
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000302 Valid = false;
303 }
304
305 if (Res1 == 0)
306 continue;
307
308 unsigned k = j;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000309 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000310 ++k, ++K, ++TripleNumber) {
311 if (K == J)
312 continue;
313
314 Function *F3 = cast<Function>(*K);
JF Bastien057292a2015-08-21 23:27:24 +0000315 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
316 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000317
318 bool Transitive = true;
319
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000320 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000321 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000322 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000323 } else if (Res3 != 0 && Res3 == -Res4) {
324 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000325 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000326 } else if (Res4 != 0 && -Res3 == Res4) {
327 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000328 Transitive = Res4 == -Res1;
329 }
330
331 if (!Transitive) {
332 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
333 << TripleNumber << "\n";
334 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
335 << Res4 << "\n";
Matthias Braun194ded52017-01-28 06:53:55 +0000336 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000337 Valid = false;
338 }
339 }
340 }
341 }
342
343 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
344 return Valid;
345 }
346 return true;
347}
Davide Italianob6681e22017-04-28 19:39:45 +0000348#endif
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000349
Nick Lewycky564fcca2011-01-28 07:36:21 +0000350bool MergeFunctions::runOnModule(Module &M) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000351 if (skipModule(M))
352 return false;
353
Nick Lewycky564fcca2011-01-28 07:36:21 +0000354 bool Changed = false;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000355
JF Bastien5e4303d2015-08-15 01:18:18 +0000356 // All functions in the module, ordered by hash. Functions with a unique
357 // hash value are easily eliminated.
358 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
359 HashedFuncs;
360 for (Function &Func : M) {
361 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
362 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
363 }
Nick Lewycky564fcca2011-01-28 07:36:21 +0000364 }
Nick Lewycky564fcca2011-01-28 07:36:21 +0000365
NAKAMURA Takumi51962752015-08-16 02:41:23 +0000366 std::stable_sort(
367 HashedFuncs.begin(), HashedFuncs.end(),
368 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
369 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
370 return a.first < b.first;
371 });
JF Bastien5e4303d2015-08-15 01:18:18 +0000372
373 auto S = HashedFuncs.begin();
374 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
375 // If the hash value matches the previous value or the next one, we must
376 // consider merging it. Otherwise it is dropped and never considered again.
377 if ((I != S && std::prev(I)->first == I->first) ||
378 (std::next(I) != IE && std::next(I)->first == I->first) ) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000379 Deferred.push_back(WeakTrackingVH(I->second));
JF Bastien5e4303d2015-08-15 01:18:18 +0000380 }
381 }
382
Nick Lewycky564fcca2011-01-28 07:36:21 +0000383 do {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000384 std::vector<WeakTrackingVH> Worklist;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000385 Deferred.swap(Worklist);
386
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000387 DEBUG(doSanityCheck(Worklist));
388
Nick Lewycky564fcca2011-01-28 07:36:21 +0000389 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
390 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
391
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000392 // Insert functions and merge them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000393 for (WeakTrackingVH &I : Worklist) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000394 if (!I)
395 continue;
396 Function *F = cast<Function>(I);
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000397 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000398 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000399 }
400 }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000401 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +0000402 } while (!Deferred.empty());
403
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000404 FnTree.clear();
Arnold Schwaighofer0591c5d2015-10-05 17:26:36 +0000405 GlobalNumbers.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +0000406
407 return Changed;
408}
409
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000410// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000411void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
412 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000413 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
414 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000415 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000416 CallSite CS(U->getUser());
417 if (CS && CS.isCallee(U)) {
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000418 // Transfer the called function's attributes to the call site. Due to the
JF Bastienfa946232015-09-10 18:08:35 +0000419 // bitcast we will 'lose' ABI changing attributes because the 'called
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000420 // function' is no longer a Function* but the bitcast. Code that looks up
421 // the attributes from the called function will fail.
JF Bastienfa946232015-09-10 18:08:35 +0000422
423 // FIXME: This is not actually true, at least not anymore. The callsite
424 // will always have the same ABI affecting attributes as the callee,
425 // because otherwise the original input has UB. Note that Old and New
426 // always have matching ABI, so no attributes need to be changed.
427 // Transferring other attributes may help other optimizations, but that
428 // should be done uniformly and not in this ad-hoc way.
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000429 auto &Context = New->getContext();
Reid Klecknerf021fab2017-04-13 23:12:13 +0000430 auto NewPAL = New->getAttributes();
431 SmallVector<AttributeSet, 4> NewArgAttrs;
432 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++)
433 NewArgAttrs.push_back(NewPAL.getParamAttributes(argIdx));
434 // Don't transfer attributes from the function to the callee. Function
435 // attributes typically aren't relevant to the calling convention or ABI.
436 CS.setAttributes(AttributeList::get(Context, /*FnAttrs=*/AttributeSet(),
437 NewPAL.getRetAttributes(),
438 NewArgAttrs));
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000439
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000440 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000441 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000442 }
443 }
444}
445
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000446// Helper for writeThunk,
447// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +0000448// but a bit simpler then CastInst::getCastOpcode.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000449static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000450 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +0000451 if (SrcTy->isStructTy()) {
452 assert(DestTy->isStructTy());
453 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
454 Value *Result = UndefValue::get(DestTy);
455 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
456 Value *Element = createCast(
Craig Toppere1d12942014-08-27 05:25:25 +0000457 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
Carlo Kok307625c2014-04-30 17:53:04 +0000458 DestTy->getStructElementType(I));
459
460 Result =
Craig Toppere1d12942014-08-27 05:25:25 +0000461 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
Carlo Kok307625c2014-04-30 17:53:04 +0000462 }
463 return Result;
464 }
465 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000466 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
467 return Builder.CreateIntToPtr(V, DestTy);
468 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
469 return Builder.CreatePtrToInt(V, DestTy);
470 else
471 return Builder.CreateBitCast(V, DestTy);
472}
473
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000474// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
475// parameter debug info, from the entry block.
476void MergeFunctions::eraseInstsUnrelatedToPDI(
477 std::vector<Instruction *> &PDIUnrelatedWL) {
478
479 DEBUG(dbgs() << " Erasing instructions (in reverse order of appearance in "
480 "entry block) unrelated to parameter debug info from entry "
481 "block: {\n");
482 while (!PDIUnrelatedWL.empty()) {
483 Instruction *I = PDIUnrelatedWL.back();
484 DEBUG(dbgs() << " Deleting Instruction: ");
485 DEBUG(I->print(dbgs()));
486 DEBUG(dbgs() << "\n");
487 I->eraseFromParent();
488 PDIUnrelatedWL.pop_back();
489 }
490 DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
491 "debug info from entry block. \n");
492}
493
494// Reduce G to its entry block.
495void MergeFunctions::eraseTail(Function *G) {
496
497 std::vector<BasicBlock *> WorklistBB;
498 for (Function::iterator BBI = std::next(G->begin()), BBE = G->end();
499 BBI != BBE; ++BBI) {
500 BBI->dropAllReferences();
501 WorklistBB.push_back(&*BBI);
502 }
503 while (!WorklistBB.empty()) {
504 BasicBlock *BB = WorklistBB.back();
505 BB->eraseFromParent();
506 WorklistBB.pop_back();
507 }
508}
509
510// We are interested in the following instructions from the entry block as being
511// related to parameter debug info:
512// - @llvm.dbg.declare
513// - stores from the incoming parameters to locations on the stack-frame
514// - allocas that create these locations on the stack-frame
515// - @llvm.dbg.value
516// - the entry block's terminator
517// The rest are unrelated to debug info for the parameters; fill up
518// PDIUnrelatedWL with such instructions.
519void MergeFunctions::filterInstsUnrelatedToPDI(
520 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
521
522 std::set<Instruction *> PDIRelated;
523 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
524 BI != BIE; ++BI) {
525 if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
526 DEBUG(dbgs() << " Deciding: ");
527 DEBUG(BI->print(dbgs()));
528 DEBUG(dbgs() << "\n");
529 DILocalVariable *DILocVar = DVI->getVariable();
530 if (DILocVar->isParameter()) {
531 DEBUG(dbgs() << " Include (parameter): ");
532 DEBUG(BI->print(dbgs()));
533 DEBUG(dbgs() << "\n");
534 PDIRelated.insert(&*BI);
535 } else {
536 DEBUG(dbgs() << " Delete (!parameter): ");
537 DEBUG(BI->print(dbgs()));
538 DEBUG(dbgs() << "\n");
539 }
540 } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
541 DEBUG(dbgs() << " Deciding: ");
542 DEBUG(BI->print(dbgs()));
543 DEBUG(dbgs() << "\n");
544 DILocalVariable *DILocVar = DDI->getVariable();
545 if (DILocVar->isParameter()) {
546 DEBUG(dbgs() << " Parameter: ");
547 DEBUG(DILocVar->print(dbgs()));
548 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
549 if (AI) {
550 DEBUG(dbgs() << " Processing alloca users: ");
551 DEBUG(dbgs() << "\n");
552 for (User *U : AI->users()) {
553 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
554 if (Value *Arg = SI->getValueOperand()) {
555 if (dyn_cast<Argument>(Arg)) {
556 DEBUG(dbgs() << " Include: ");
557 DEBUG(AI->print(dbgs()));
558 DEBUG(dbgs() << "\n");
559 PDIRelated.insert(AI);
560 DEBUG(dbgs() << " Include (parameter): ");
561 DEBUG(SI->print(dbgs()));
562 DEBUG(dbgs() << "\n");
563 PDIRelated.insert(SI);
564 DEBUG(dbgs() << " Include: ");
565 DEBUG(BI->print(dbgs()));
566 DEBUG(dbgs() << "\n");
567 PDIRelated.insert(&*BI);
568 } else {
569 DEBUG(dbgs() << " Delete (!parameter): ");
570 DEBUG(SI->print(dbgs()));
571 DEBUG(dbgs() << "\n");
572 }
573 }
574 } else {
575 DEBUG(dbgs() << " Defer: ");
576 DEBUG(U->print(dbgs()));
577 DEBUG(dbgs() << "\n");
578 }
579 }
580 } else {
581 DEBUG(dbgs() << " Delete (alloca NULL): ");
582 DEBUG(BI->print(dbgs()));
583 DEBUG(dbgs() << "\n");
584 }
585 } else {
586 DEBUG(dbgs() << " Delete (!parameter): ");
587 DEBUG(BI->print(dbgs()));
588 DEBUG(dbgs() << "\n");
589 }
590 } else if (dyn_cast<TerminatorInst>(BI) == GEntryBlock->getTerminator()) {
591 DEBUG(dbgs() << " Will Include Terminator: ");
592 DEBUG(BI->print(dbgs()));
593 DEBUG(dbgs() << "\n");
594 PDIRelated.insert(&*BI);
595 } else {
596 DEBUG(dbgs() << " Defer: ");
597 DEBUG(BI->print(dbgs()));
598 DEBUG(dbgs() << "\n");
599 }
600 }
601 DEBUG(dbgs()
602 << " Report parameter debug info related/related instructions: {\n");
603 for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end();
604 BI != BE; ++BI) {
605
606 Instruction *I = &*BI;
607 if (PDIRelated.find(I) == PDIRelated.end()) {
608 DEBUG(dbgs() << " !PDIRelated: ");
609 DEBUG(I->print(dbgs()));
610 DEBUG(dbgs() << "\n");
611 PDIUnrelatedWL.push_back(I);
612 } else {
613 DEBUG(dbgs() << " PDIRelated: ");
614 DEBUG(I->print(dbgs()));
615 DEBUG(dbgs() << "\n");
616 }
617 }
618 DEBUG(dbgs() << " }\n");
619}
620
621// Replace G with a simple tail call to bitcast(F). Also (unless
622// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
623// delete G. Under MergeFunctionsPDI, we use G itself for creating
624// the thunk as we preserve the debug info (and associated instructions)
625// from G's entry block pertaining to G's incoming arguments which are
626// passed on as corresponding arguments in the call that G makes to F.
627// For better debugability, under MergeFunctionsPDI, we do not modify G's
628// call sites to point to F even when within the same translation unit.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000629void MergeFunctions::writeThunk(Function *F, Function *G) {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000630 if (!G->isInterposable() && !MergeFunctionsPDI) {
631 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
632 // above).
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000633 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000634 }
635
Nick Lewycky71972d42010-09-07 01:42:10 +0000636 // If G was internal then we may have replaced all uses of G with F. If so,
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000637 // stop here and delete G. There's no need for a thunk. (See note on
638 // MergeFunctionsPDI above).
639 if (G->hasLocalLinkage() && G->use_empty() && !MergeFunctionsPDI) {
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000640 G->eraseFromParent();
641 return;
642 }
643
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000644 BasicBlock *GEntryBlock = nullptr;
645 std::vector<Instruction *> PDIUnrelatedWL;
646 BasicBlock *BB = nullptr;
647 Function *NewG = nullptr;
648 if (MergeFunctionsPDI) {
649 DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
650 "function as thunk; retain original: "
651 << G->getName() << "()\n");
652 GEntryBlock = &G->getEntryBlock();
653 DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
654 "debug info for "
655 << G->getName() << "() {\n");
656 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
657 GEntryBlock->getTerminator()->eraseFromParent();
658 BB = GEntryBlock;
659 } else {
660 NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
661 G->getParent());
662 BB = BasicBlock::Create(F->getContext(), "", NewG);
663 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000664
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000665 IRBuilder<> Builder(BB);
666 Function *H = MergeFunctionsPDI ? G : NewG;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000667 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000668 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000669 FunctionType *FFTy = F->getFunctionType();
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000670 for (Argument & AI : H->args()) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000671 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +0000672 ++i;
673 }
674
Jay Foad5bd375a2011-07-15 08:37:34 +0000675 CallInst *CI = Builder.CreateCall(F, Args);
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000676 ReturnInst *RI = nullptr;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000677 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +0000678 CI->setCallingConv(F->getCallingConv());
JF Bastienfa946232015-09-10 18:08:35 +0000679 CI->setAttributes(F->getAttributes());
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000680 if (H->getReturnType()->isVoidTy()) {
681 RI = Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +0000682 } else {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000683 RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +0000684 }
685
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000686 if (MergeFunctionsPDI) {
687 DISubprogram *DIS = G->getSubprogram();
688 if (DIS) {
689 DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
690 DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
691 CI->setDebugLoc(CIDbgLoc);
692 RI->setDebugLoc(RIDbgLoc);
693 } else {
694 DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
695 << G->getName() << "()\n");
696 }
697 eraseTail(G);
698 eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
699 DEBUG(dbgs() << "} // End of parameter related debug info filtering for: "
700 << G->getName() << "()\n");
701 } else {
702 NewG->copyAttributesFrom(G);
703 NewG->takeName(G);
704 removeUsers(G);
705 G->replaceAllUsesWith(NewG);
706 G->eraseFromParent();
707 }
Nick Lewycky71972d42010-09-07 01:42:10 +0000708
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000709 DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +0000710 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000711}
712
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000713// Merge two equivalent functions. Upon completion, Function G is deleted.
714void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000715 if (F->isInterposable()) {
716 assert(G->isInterposable());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000717
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000718 // Make them both thunks to the same internal function.
719 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
720 F->getParent());
721 H->copyAttributesFrom(F);
722 H->takeName(F);
723 removeUsers(F);
724 F->replaceAllUsesWith(H);
725
726 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
727
whitequark9e8197a2017-07-27 19:36:13 +0000728 writeThunk(F, G);
729 writeThunk(F, H);
Nick Lewycky71972d42010-09-07 01:42:10 +0000730
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000731 F->setAlignment(MaxAlignment);
732 F->setLinkage(GlobalValue::PrivateLinkage);
Nick Lewycky71972d42010-09-07 01:42:10 +0000733 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000734 } else {
whitequark9e8197a2017-07-27 19:36:13 +0000735 writeThunk(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +0000736 }
737
Nick Lewyckye04dc222009-06-12 08:04:51 +0000738 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000739}
740
JF Bastien3a4ad612015-09-02 23:55:23 +0000741/// Replace function F by function G.
742void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000743 Function *G) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000744 Function *F = FN.getFunc();
JF Bastien057292a2015-08-21 23:27:24 +0000745 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
746 "The two functions must be equal");
JF Bastien3a4ad612015-09-02 23:55:23 +0000747
748 auto I = FNodesInTree.find(F);
749 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
750 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
751
752 FnTreeType::iterator IterToFNInFnTree = I->second;
753 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
754 // Remove F -> FN and insert G -> FN
755 FNodesInTree.erase(I);
756 FNodesInTree.insert({G, IterToFNInFnTree});
757 // Replace F with G in FN, which is stored inside the FnTree.
758 FN.replaceBy(G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000759}
760
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000761// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000762// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000763bool MergeFunctions::insert(Function *NewFunction) {
764 std::pair<FnTreeType::iterator, bool> Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000765 FnTree.insert(FunctionNode(NewFunction));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000766
Nick Lewycky292e78c2011-02-09 06:32:02 +0000767 if (Result.second) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000768 assert(FNodesInTree.count(NewFunction) == 0);
769 FNodesInTree.insert({NewFunction, Result.first});
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000770 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +0000771 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +0000772 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000773
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000774 const FunctionNode &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +0000775
Matt Arsenault517d84e2013-10-01 18:05:30 +0000776 // Don't merge tiny functions, since it can just end up making the function
777 // larger.
778 // FIXME: Should still merge them if they are unnamed_addr and produce an
779 // alias.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000780 if (NewFunction->size() == 1) {
781 if (NewFunction->front().size() <= 2) {
782 DEBUG(dbgs() << NewFunction->getName()
783 << " is to small to bother merging\n");
Matt Arsenault517d84e2013-10-01 18:05:30 +0000784 return false;
785 }
786 }
787
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000788 // Impose a total order (by name) on the replacement of functions. This is
789 // important when operating on more than one module independently to prevent
790 // cycles of thunks calling each other when the modules are linked together.
791 //
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000792 // First of all, we process strong functions before weak functions.
793 if ((OldF.getFunc()->isInterposable() && !NewFunction->isInterposable()) ||
794 (OldF.getFunc()->isInterposable() == NewFunction->isInterposable() &&
795 OldF.getFunc()->getName() > NewFunction->getName())) {
796 // Swap the two functions.
797 Function *F = OldF.getFunc();
798 replaceFunctionInTree(*Result.first, NewFunction);
799 NewFunction = F;
800 assert(OldF.getFunc() != F && "Must have swapped the functions.");
801 }
Nick Lewycky00959372010-09-05 08:22:49 +0000802
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000803 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
804 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +0000805
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000806 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000807 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +0000808 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000809}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000810
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000811// Remove a function from FnTree. If it was already in FnTree, add
812// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000813void MergeFunctions::remove(Function *F) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000814 auto I = FNodesInTree.find(F);
815 if (I != FNodesInTree.end()) {
816 DEBUG(dbgs() << "Deferred " << F->getName()<< ".\n");
817 FnTree.erase(I->second);
818 // I->second has been invalidated, remove it from the FNodesInTree map to
819 // preserve the invariant.
820 FNodesInTree.erase(I);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000821 Deferred.emplace_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000822 }
Nick Lewycky4e250c82011-01-02 02:46:33 +0000823}
Nick Lewycky00959372010-09-05 08:22:49 +0000824
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000825// For each instruction used by the value, remove() the function that contains
826// the instruction. This should happen right before a call to RAUW.
827void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +0000828 std::vector<Value *> Worklist;
829 Worklist.push_back(V);
JF Bastien7289f732015-07-15 21:51:33 +0000830 SmallSet<Value*, 8> Visited;
831 Visited.insert(V);
Nick Lewycky5361b842011-01-02 19:16:44 +0000832 while (!Worklist.empty()) {
833 Value *V = Worklist.back();
834 Worklist.pop_back();
835
Chandler Carruthcdf47882014-03-09 03:16:01 +0000836 for (User *U : V->users()) {
837 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000838 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000839 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +0000840 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +0000841 } else if (Constant *C = dyn_cast<Constant>(U)) {
JF Bastien7289f732015-07-15 21:51:33 +0000842 for (User *UU : C->users()) {
843 if (!Visited.insert(UU).second)
844 Worklist.push_back(UU);
845 }
Nick Lewycky5361b842011-01-02 19:16:44 +0000846 }
Nick Lewycky00959372010-09-05 08:22:49 +0000847 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000848 }
Nick Lewycky00959372010-09-05 08:22:49 +0000849}