blob: 43c8ce39af326b330d117d9f5035bba35acedb78 [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");
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000122STATISTIC(NumAliasesWritten, "Number of aliases generated");
Nick Lewycky71972d42010-09-07 01:42:10 +0000123STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000124
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000125static cl::opt<unsigned> NumFunctionsForSanityCheck(
126 "mergefunc-sanity",
127 cl::desc("How many functions in module could be used for "
128 "MergeFunctions pass sanity check. "
129 "'0' disables this check. Works only with '-debug' key."),
130 cl::init(0), cl::Hidden);
131
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000132// Under option -mergefunc-preserve-debug-info we:
133// - Do not create a new function for a thunk.
134// - Retain the debug info for a thunk's parameters (and associated
135// instructions for the debug info) from the entry block.
136// Note: -debug will display the algorithm at work.
137// - Create debug-info for the call (to the shared implementation) made by
138// a thunk and its return value.
139// - Erase the rest of the function, retaining the (minimally sized) entry
140// block to create a thunk.
141// - Preserve a thunk's call site to point to the thunk even when both occur
142// within the same translation unit, to aid debugability. Note that this
143// behaviour differs from the underlying -mergefunc implementation which
144// modifies the thunk's call site to point to the shared implementation
145// when both occur within the same translation unit.
146static cl::opt<bool>
147 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
148 cl::init(false),
149 cl::desc("Preserve debug info in thunk when mergefunc "
150 "transformations are made."));
151
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000152namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000153
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000154class FunctionNode {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000155 mutable AssertingVH<Function> F;
JF Bastien5e4303d2015-08-15 01:18:18 +0000156 FunctionComparator::FunctionHash Hash;
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000157public:
JF Bastien5e4303d2015-08-15 01:18:18 +0000158 // Note the hash is recalculated potentially multiple times, but it is cheap.
JF Bastien057292a2015-08-21 23:27:24 +0000159 FunctionNode(Function *F)
160 : F(F), Hash(FunctionComparator::functionHash(*F)) {}
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000161 Function *getFunc() const { return F; }
JF Bastien057292a2015-08-21 23:27:24 +0000162 FunctionComparator::FunctionHash getHash() const { return Hash; }
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000163
164 /// Replace the reference to the function F by the function G, assuming their
165 /// implementations are equal.
166 void replaceBy(Function *G) const {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000167 F = G;
168 }
169
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000170 void release() { F = nullptr; }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000171};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000172
173/// MergeFunctions finds functions which will generate identical machine code,
174/// by considering all pointer types to be equivalent. Once identified,
175/// MergeFunctions will fold them by replacing a call to one to a call to a
176/// bitcast of the other.
177///
178class MergeFunctions : public ModulePass {
179public:
180 static char ID;
181 MergeFunctions()
JF Bastien3a4ad612015-09-02 23:55:23 +0000182 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)), FNodesInTree(),
JF Bastien057292a2015-08-21 23:27:24 +0000183 HasGlobalAliases(false) {
Nick Lewycky564fcca2011-01-28 07:36:21 +0000184 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
185 }
186
Craig Topper3e4c6972014-03-05 09:10:37 +0000187 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000188
189private:
JF Bastien057292a2015-08-21 23:27:24 +0000190 // The function comparison operator is provided here so that FunctionNodes do
191 // not need to become larger with another pointer.
192 class FunctionNodeCmp {
193 GlobalNumberState* GlobalNumbers;
194 public:
195 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
196 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
197 // Order first by hashes, then full function comparison.
198 if (LHS.getHash() != RHS.getHash())
199 return LHS.getHash() < RHS.getHash();
200 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
201 return FCmp.compare() == -1;
202 }
203 };
204 typedef std::set<FunctionNode, FunctionNodeCmp> FnTreeType;
205
206 GlobalNumberState GlobalNumbers;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000207
208 /// A work queue of functions that may have been modified and should be
209 /// analyzed again.
210 std::vector<WeakVH> Deferred;
211
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000212 /// Checks the rules of order relation introduced among functions set.
213 /// Returns true, if sanity check has been passed, and false if failed.
214 bool doSanityCheck(std::vector<WeakVH> &Worklist);
215
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
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000237 /// Replace G with a thunk or an alias to F. Deletes G.
238 void writeThunkOrAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000239
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000240 /// Fill PDIUnrelatedWL with instructions from the entry block that are
241 /// unrelated to parameter related debug info.
242 void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
243 std::vector<Instruction *> &PDIUnrelatedWL);
244
245 /// Erase the rest of the CFG (i.e. barring the entry block).
246 void eraseTail(Function *G);
247
248 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
249 /// parameter debug info, from the entry block.
250 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
251
252 /// Replace G with a simple tail call to bitcast(F). Also (unless
253 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
254 /// delete G.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000255 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000256
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000257 /// Replace G with an alias to F. Deletes G.
258 void writeAlias(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000259
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000260 /// Replace function F with function G in the function tree.
JF Bastien3a4ad612015-09-02 23:55:23 +0000261 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000262
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000263 /// The set of all distinct functions. Use the insert() and remove() methods
JF Bastien3a4ad612015-09-02 23:55:23 +0000264 /// to modify it. The map allows efficient lookup and deferring of Functions.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000265 FnTreeType FnTree;
JF Bastien3a4ad612015-09-02 23:55:23 +0000266 // Map functions to the iterators of the FunctionNode which contains them
267 // in the FnTree. This must be updated carefully whenever the FnTree is
268 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
269 // dangling iterators into FnTree. The invariant that preserves this is that
270 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
271 ValueMap<Function*, FnTreeType::iterator> FNodesInTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000272
Nick Lewycky564fcca2011-01-28 07:36:21 +0000273 /// Whether or not the target supports global aliases.
274 bool HasGlobalAliases;
275};
276
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000277} // end anonymous namespace
Nick Lewycky564fcca2011-01-28 07:36:21 +0000278
279char MergeFunctions::ID = 0;
280INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
281
282ModulePass *llvm::createMergeFunctionsPass() {
283 return new MergeFunctions();
284}
285
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000286bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
287 if (const unsigned Max = NumFunctionsForSanityCheck) {
288 unsigned TripleNumber = 0;
289 bool Valid = true;
290
291 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
292
293 unsigned i = 0;
294 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
295 I != E && i < Max; ++I, ++i) {
296 unsigned j = i;
297 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
298 Function *F1 = cast<Function>(*I);
299 Function *F2 = cast<Function>(*J);
JF Bastien057292a2015-08-21 23:27:24 +0000300 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
301 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000302
303 // If F1 <= F2, then F2 >= F1, otherwise report failure.
304 if (Res1 != -Res2) {
305 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
306 << "\n";
307 F1->dump();
308 F2->dump();
309 Valid = false;
310 }
311
312 if (Res1 == 0)
313 continue;
314
315 unsigned k = j;
316 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
317 ++k, ++K, ++TripleNumber) {
318 if (K == J)
319 continue;
320
321 Function *F3 = cast<Function>(*K);
JF Bastien057292a2015-08-21 23:27:24 +0000322 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
323 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000324
325 bool Transitive = true;
326
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000327 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000328 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000329 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000330 } else if (Res3 != 0 && Res3 == -Res4) {
331 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000332 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000333 } else if (Res4 != 0 && -Res3 == Res4) {
334 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000335 Transitive = Res4 == -Res1;
336 }
337
338 if (!Transitive) {
339 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
340 << TripleNumber << "\n";
341 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
342 << Res4 << "\n";
343 F1->dump();
344 F2->dump();
345 F3->dump();
346 Valid = false;
347 }
348 }
349 }
350 }
351
352 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
353 return Valid;
354 }
355 return true;
356}
357
Nick Lewycky564fcca2011-01-28 07:36:21 +0000358bool MergeFunctions::runOnModule(Module &M) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000359 if (skipModule(M))
360 return false;
361
Nick Lewycky564fcca2011-01-28 07:36:21 +0000362 bool Changed = false;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000363
JF Bastien5e4303d2015-08-15 01:18:18 +0000364 // All functions in the module, ordered by hash. Functions with a unique
365 // hash value are easily eliminated.
366 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
367 HashedFuncs;
368 for (Function &Func : M) {
369 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
370 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
371 }
Nick Lewycky564fcca2011-01-28 07:36:21 +0000372 }
Nick Lewycky564fcca2011-01-28 07:36:21 +0000373
NAKAMURA Takumi51962752015-08-16 02:41:23 +0000374 std::stable_sort(
375 HashedFuncs.begin(), HashedFuncs.end(),
376 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
377 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
378 return a.first < b.first;
379 });
JF Bastien5e4303d2015-08-15 01:18:18 +0000380
381 auto S = HashedFuncs.begin();
382 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
383 // If the hash value matches the previous value or the next one, we must
384 // consider merging it. Otherwise it is dropped and never considered again.
385 if ((I != S && std::prev(I)->first == I->first) ||
386 (std::next(I) != IE && std::next(I)->first == I->first) ) {
387 Deferred.push_back(WeakVH(I->second));
388 }
389 }
390
Nick Lewycky564fcca2011-01-28 07:36:21 +0000391 do {
392 std::vector<WeakVH> Worklist;
393 Deferred.swap(Worklist);
394
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000395 DEBUG(doSanityCheck(Worklist));
396
Nick Lewycky564fcca2011-01-28 07:36:21 +0000397 DEBUG(dbgs() << "size of module: " << M.size() << '\n');
398 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
399
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000400 // Insert functions and merge them.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000401 for (WeakVH &I : Worklist) {
402 if (!I)
403 continue;
404 Function *F = cast<Function>(I);
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000405 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000406 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000407 }
408 }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000409 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +0000410 } while (!Deferred.empty());
411
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000412 FnTree.clear();
Arnold Schwaighofer0591c5d2015-10-05 17:26:36 +0000413 GlobalNumbers.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +0000414
415 return Changed;
416}
417
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000418// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000419void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
420 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000421 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
422 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000423 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000424 CallSite CS(U->getUser());
425 if (CS && CS.isCallee(U)) {
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000426 // Transfer the called function's attributes to the call site. Due to the
JF Bastienfa946232015-09-10 18:08:35 +0000427 // bitcast we will 'lose' ABI changing attributes because the 'called
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000428 // function' is no longer a Function* but the bitcast. Code that looks up
429 // the attributes from the called function will fail.
JF Bastienfa946232015-09-10 18:08:35 +0000430
431 // FIXME: This is not actually true, at least not anymore. The callsite
432 // will always have the same ABI affecting attributes as the callee,
433 // because otherwise the original input has UB. Note that Old and New
434 // always have matching ABI, so no attributes need to be changed.
435 // Transferring other attributes may help other optimizations, but that
436 // should be done uniformly and not in this ad-hoc way.
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000437 auto &Context = New->getContext();
438 auto NewFuncAttrs = New->getAttributes();
439 auto CallSiteAttrs = CS.getAttributes();
440
441 CallSiteAttrs = CallSiteAttrs.addAttributes(
442 Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes());
443
444 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) {
445 AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx);
446 if (Attrs.getNumSlots())
447 CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs);
448 }
449
450 CS.setAttributes(CallSiteAttrs);
451
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000452 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000453 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000454 }
455 }
456}
457
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000458// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
459void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000460 if (HasGlobalAliases && G->hasGlobalUnnamedAddr()) {
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000461 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
462 G->hasWeakLinkage()) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000463 writeAlias(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000464 return;
465 }
466 }
467
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000468 writeThunk(F, G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000469}
470
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000471// Helper for writeThunk,
472// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +0000473// but a bit simpler then CastInst::getCastOpcode.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000474static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000475 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +0000476 if (SrcTy->isStructTy()) {
477 assert(DestTy->isStructTy());
478 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
479 Value *Result = UndefValue::get(DestTy);
480 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
481 Value *Element = createCast(
Craig Toppere1d12942014-08-27 05:25:25 +0000482 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
Carlo Kok307625c2014-04-30 17:53:04 +0000483 DestTy->getStructElementType(I));
484
485 Result =
Craig Toppere1d12942014-08-27 05:25:25 +0000486 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
Carlo Kok307625c2014-04-30 17:53:04 +0000487 }
488 return Result;
489 }
490 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000491 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
492 return Builder.CreateIntToPtr(V, DestTy);
493 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
494 return Builder.CreatePtrToInt(V, DestTy);
495 else
496 return Builder.CreateBitCast(V, DestTy);
497}
498
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000499// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
500// parameter debug info, from the entry block.
501void MergeFunctions::eraseInstsUnrelatedToPDI(
502 std::vector<Instruction *> &PDIUnrelatedWL) {
503
504 DEBUG(dbgs() << " Erasing instructions (in reverse order of appearance in "
505 "entry block) unrelated to parameter debug info from entry "
506 "block: {\n");
507 while (!PDIUnrelatedWL.empty()) {
508 Instruction *I = PDIUnrelatedWL.back();
509 DEBUG(dbgs() << " Deleting Instruction: ");
510 DEBUG(I->print(dbgs()));
511 DEBUG(dbgs() << "\n");
512 I->eraseFromParent();
513 PDIUnrelatedWL.pop_back();
514 }
515 DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
516 "debug info from entry block. \n");
517}
518
519// Reduce G to its entry block.
520void MergeFunctions::eraseTail(Function *G) {
521
522 std::vector<BasicBlock *> WorklistBB;
523 for (Function::iterator BBI = std::next(G->begin()), BBE = G->end();
524 BBI != BBE; ++BBI) {
525 BBI->dropAllReferences();
526 WorklistBB.push_back(&*BBI);
527 }
528 while (!WorklistBB.empty()) {
529 BasicBlock *BB = WorklistBB.back();
530 BB->eraseFromParent();
531 WorklistBB.pop_back();
532 }
533}
534
535// We are interested in the following instructions from the entry block as being
536// related to parameter debug info:
537// - @llvm.dbg.declare
538// - stores from the incoming parameters to locations on the stack-frame
539// - allocas that create these locations on the stack-frame
540// - @llvm.dbg.value
541// - the entry block's terminator
542// The rest are unrelated to debug info for the parameters; fill up
543// PDIUnrelatedWL with such instructions.
544void MergeFunctions::filterInstsUnrelatedToPDI(
545 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
546
547 std::set<Instruction *> PDIRelated;
548 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
549 BI != BIE; ++BI) {
550 if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
551 DEBUG(dbgs() << " Deciding: ");
552 DEBUG(BI->print(dbgs()));
553 DEBUG(dbgs() << "\n");
554 DILocalVariable *DILocVar = DVI->getVariable();
555 if (DILocVar->isParameter()) {
556 DEBUG(dbgs() << " Include (parameter): ");
557 DEBUG(BI->print(dbgs()));
558 DEBUG(dbgs() << "\n");
559 PDIRelated.insert(&*BI);
560 } else {
561 DEBUG(dbgs() << " Delete (!parameter): ");
562 DEBUG(BI->print(dbgs()));
563 DEBUG(dbgs() << "\n");
564 }
565 } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
566 DEBUG(dbgs() << " Deciding: ");
567 DEBUG(BI->print(dbgs()));
568 DEBUG(dbgs() << "\n");
569 DILocalVariable *DILocVar = DDI->getVariable();
570 if (DILocVar->isParameter()) {
571 DEBUG(dbgs() << " Parameter: ");
572 DEBUG(DILocVar->print(dbgs()));
573 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
574 if (AI) {
575 DEBUG(dbgs() << " Processing alloca users: ");
576 DEBUG(dbgs() << "\n");
577 for (User *U : AI->users()) {
578 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
579 if (Value *Arg = SI->getValueOperand()) {
580 if (dyn_cast<Argument>(Arg)) {
581 DEBUG(dbgs() << " Include: ");
582 DEBUG(AI->print(dbgs()));
583 DEBUG(dbgs() << "\n");
584 PDIRelated.insert(AI);
585 DEBUG(dbgs() << " Include (parameter): ");
586 DEBUG(SI->print(dbgs()));
587 DEBUG(dbgs() << "\n");
588 PDIRelated.insert(SI);
589 DEBUG(dbgs() << " Include: ");
590 DEBUG(BI->print(dbgs()));
591 DEBUG(dbgs() << "\n");
592 PDIRelated.insert(&*BI);
593 } else {
594 DEBUG(dbgs() << " Delete (!parameter): ");
595 DEBUG(SI->print(dbgs()));
596 DEBUG(dbgs() << "\n");
597 }
598 }
599 } else {
600 DEBUG(dbgs() << " Defer: ");
601 DEBUG(U->print(dbgs()));
602 DEBUG(dbgs() << "\n");
603 }
604 }
605 } else {
606 DEBUG(dbgs() << " Delete (alloca NULL): ");
607 DEBUG(BI->print(dbgs()));
608 DEBUG(dbgs() << "\n");
609 }
610 } else {
611 DEBUG(dbgs() << " Delete (!parameter): ");
612 DEBUG(BI->print(dbgs()));
613 DEBUG(dbgs() << "\n");
614 }
615 } else if (dyn_cast<TerminatorInst>(BI) == GEntryBlock->getTerminator()) {
616 DEBUG(dbgs() << " Will Include Terminator: ");
617 DEBUG(BI->print(dbgs()));
618 DEBUG(dbgs() << "\n");
619 PDIRelated.insert(&*BI);
620 } else {
621 DEBUG(dbgs() << " Defer: ");
622 DEBUG(BI->print(dbgs()));
623 DEBUG(dbgs() << "\n");
624 }
625 }
626 DEBUG(dbgs()
627 << " Report parameter debug info related/related instructions: {\n");
628 for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end();
629 BI != BE; ++BI) {
630
631 Instruction *I = &*BI;
632 if (PDIRelated.find(I) == PDIRelated.end()) {
633 DEBUG(dbgs() << " !PDIRelated: ");
634 DEBUG(I->print(dbgs()));
635 DEBUG(dbgs() << "\n");
636 PDIUnrelatedWL.push_back(I);
637 } else {
638 DEBUG(dbgs() << " PDIRelated: ");
639 DEBUG(I->print(dbgs()));
640 DEBUG(dbgs() << "\n");
641 }
642 }
643 DEBUG(dbgs() << " }\n");
644}
645
646// Replace G with a simple tail call to bitcast(F). Also (unless
647// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
648// delete G. Under MergeFunctionsPDI, we use G itself for creating
649// the thunk as we preserve the debug info (and associated instructions)
650// from G's entry block pertaining to G's incoming arguments which are
651// passed on as corresponding arguments in the call that G makes to F.
652// For better debugability, under MergeFunctionsPDI, we do not modify G's
653// call sites to point to F even when within the same translation unit.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000654void MergeFunctions::writeThunk(Function *F, Function *G) {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000655 if (!G->isInterposable() && !MergeFunctionsPDI) {
656 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
657 // above).
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000658 replaceDirectCallers(G, F);
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000659 }
660
Nick Lewycky71972d42010-09-07 01:42:10 +0000661 // 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 +0000662 // stop here and delete G. There's no need for a thunk. (See note on
663 // MergeFunctionsPDI above).
664 if (G->hasLocalLinkage() && G->use_empty() && !MergeFunctionsPDI) {
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000665 G->eraseFromParent();
666 return;
667 }
668
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000669 BasicBlock *GEntryBlock = nullptr;
670 std::vector<Instruction *> PDIUnrelatedWL;
671 BasicBlock *BB = nullptr;
672 Function *NewG = nullptr;
673 if (MergeFunctionsPDI) {
674 DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
675 "function as thunk; retain original: "
676 << G->getName() << "()\n");
677 GEntryBlock = &G->getEntryBlock();
678 DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
679 "debug info for "
680 << G->getName() << "() {\n");
681 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
682 GEntryBlock->getTerminator()->eraseFromParent();
683 BB = GEntryBlock;
684 } else {
685 NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
686 G->getParent());
687 BB = BasicBlock::Create(F->getContext(), "", NewG);
688 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000689
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000690 IRBuilder<> Builder(BB);
691 Function *H = MergeFunctionsPDI ? G : NewG;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000692 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000693 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000694 FunctionType *FFTy = F->getFunctionType();
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000695 for (Argument & AI : H->args()) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000696 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +0000697 ++i;
698 }
699
Jay Foad5bd375a2011-07-15 08:37:34 +0000700 CallInst *CI = Builder.CreateCall(F, Args);
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000701 ReturnInst *RI = nullptr;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000702 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +0000703 CI->setCallingConv(F->getCallingConv());
JF Bastienfa946232015-09-10 18:08:35 +0000704 CI->setAttributes(F->getAttributes());
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000705 if (H->getReturnType()->isVoidTy()) {
706 RI = Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +0000707 } else {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000708 RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +0000709 }
710
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000711 if (MergeFunctionsPDI) {
712 DISubprogram *DIS = G->getSubprogram();
713 if (DIS) {
714 DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
715 DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
716 CI->setDebugLoc(CIDbgLoc);
717 RI->setDebugLoc(RIDbgLoc);
718 } else {
719 DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
720 << G->getName() << "()\n");
721 }
722 eraseTail(G);
723 eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
724 DEBUG(dbgs() << "} // End of parameter related debug info filtering for: "
725 << G->getName() << "()\n");
726 } else {
727 NewG->copyAttributesFrom(G);
728 NewG->takeName(G);
729 removeUsers(G);
730 G->replaceAllUsesWith(NewG);
731 G->eraseFromParent();
732 }
Nick Lewycky71972d42010-09-07 01:42:10 +0000733
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000734 DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
Nick Lewycky71972d42010-09-07 01:42:10 +0000735 ++NumThunksWritten;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000736}
737
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000738// Replace G with an alias to F and delete G.
739void MergeFunctions::writeAlias(Function *F, Function *G) {
David Blaikie6614d8d2015-09-14 20:29:26 +0000740 auto *GA = GlobalAlias::create(G->getLinkage(), "", F);
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000741 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
742 GA->takeName(G);
743 GA->setVisibility(G->getVisibility());
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000744 removeUsers(G);
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000745 G->replaceAllUsesWith(GA);
746 G->eraseFromParent();
747
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000748 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000749 ++NumAliasesWritten;
750}
751
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000752// Merge two equivalent functions. Upon completion, Function G is deleted.
753void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000754 if (F->isInterposable()) {
755 assert(G->isInterposable());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000756
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000757 // Make them both thunks to the same internal function.
758 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
759 F->getParent());
760 H->copyAttributesFrom(F);
761 H->takeName(F);
762 removeUsers(F);
763 F->replaceAllUsesWith(H);
764
765 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
766
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000767 if (HasGlobalAliases) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000768 writeAlias(F, G);
769 writeAlias(F, H);
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000770 } else {
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000771 writeThunk(F, G);
772 writeThunk(F, H);
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000773 }
Nick Lewycky71972d42010-09-07 01:42:10 +0000774
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000775 F->setAlignment(MaxAlignment);
776 F->setLinkage(GlobalValue::PrivateLinkage);
Nick Lewycky71972d42010-09-07 01:42:10 +0000777 ++NumDoubleWeak;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000778 } else {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000779 writeThunkOrAlias(F, G);
Nick Lewycky3c6d34a2008-11-02 16:46:26 +0000780 }
781
Nick Lewyckye04dc222009-06-12 08:04:51 +0000782 ++NumFunctionsMerged;
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000783}
784
JF Bastien3a4ad612015-09-02 23:55:23 +0000785/// Replace function F by function G.
786void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000787 Function *G) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000788 Function *F = FN.getFunc();
JF Bastien057292a2015-08-21 23:27:24 +0000789 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
790 "The two functions must be equal");
JF Bastien3a4ad612015-09-02 23:55:23 +0000791
792 auto I = FNodesInTree.find(F);
793 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
794 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
795
796 FnTreeType::iterator IterToFNInFnTree = I->second;
797 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
798 // Remove F -> FN and insert G -> FN
799 FNodesInTree.erase(I);
800 FNodesInTree.insert({G, IterToFNInFnTree});
801 // Replace F with G in FN, which is stored inside the FnTree.
802 FN.replaceBy(G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000803}
804
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000805// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000806// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000807bool MergeFunctions::insert(Function *NewFunction) {
808 std::pair<FnTreeType::iterator, bool> Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000809 FnTree.insert(FunctionNode(NewFunction));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000810
Nick Lewycky292e78c2011-02-09 06:32:02 +0000811 if (Result.second) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000812 assert(FNodesInTree.count(NewFunction) == 0);
813 FNodesInTree.insert({NewFunction, Result.first});
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000814 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +0000815 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +0000816 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000817
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000818 const FunctionNode &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +0000819
Matt Arsenault517d84e2013-10-01 18:05:30 +0000820 // Don't merge tiny functions, since it can just end up making the function
821 // larger.
822 // FIXME: Should still merge them if they are unnamed_addr and produce an
823 // alias.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000824 if (NewFunction->size() == 1) {
825 if (NewFunction->front().size() <= 2) {
826 DEBUG(dbgs() << NewFunction->getName()
827 << " is to small to bother merging\n");
Matt Arsenault517d84e2013-10-01 18:05:30 +0000828 return false;
829 }
830 }
831
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000832 // Impose a total order (by name) on the replacement of functions. This is
833 // important when operating on more than one module independently to prevent
834 // cycles of thunks calling each other when the modules are linked together.
835 //
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000836 // First of all, we process strong functions before weak functions.
837 if ((OldF.getFunc()->isInterposable() && !NewFunction->isInterposable()) ||
838 (OldF.getFunc()->isInterposable() == NewFunction->isInterposable() &&
839 OldF.getFunc()->getName() > NewFunction->getName())) {
840 // Swap the two functions.
841 Function *F = OldF.getFunc();
842 replaceFunctionInTree(*Result.first, NewFunction);
843 NewFunction = F;
844 assert(OldF.getFunc() != F && "Must have swapped the functions.");
845 }
Nick Lewycky00959372010-09-05 08:22:49 +0000846
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000847 DEBUG(dbgs() << " " << OldF.getFunc()->getName()
848 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +0000849
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000850 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000851 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +0000852 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000853}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000854
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000855// Remove a function from FnTree. If it was already in FnTree, add
856// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000857void MergeFunctions::remove(Function *F) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000858 auto I = FNodesInTree.find(F);
859 if (I != FNodesInTree.end()) {
860 DEBUG(dbgs() << "Deferred " << F->getName()<< ".\n");
861 FnTree.erase(I->second);
862 // I->second has been invalidated, remove it from the FNodesInTree map to
863 // preserve the invariant.
864 FNodesInTree.erase(I);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000865 Deferred.emplace_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000866 }
Nick Lewycky4e250c82011-01-02 02:46:33 +0000867}
Nick Lewycky00959372010-09-05 08:22:49 +0000868
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000869// For each instruction used by the value, remove() the function that contains
870// the instruction. This should happen right before a call to RAUW.
871void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +0000872 std::vector<Value *> Worklist;
873 Worklist.push_back(V);
JF Bastien7289f732015-07-15 21:51:33 +0000874 SmallSet<Value*, 8> Visited;
875 Visited.insert(V);
Nick Lewycky5361b842011-01-02 19:16:44 +0000876 while (!Worklist.empty()) {
877 Value *V = Worklist.back();
878 Worklist.pop_back();
879
Chandler Carruthcdf47882014-03-09 03:16:01 +0000880 for (User *U : V->users()) {
881 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000882 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000883 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +0000884 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +0000885 } else if (Constant *C = dyn_cast<Constant>(U)) {
JF Bastien7289f732015-07-15 21:51:33 +0000886 for (User *UU : C->users()) {
887 if (!Visited.insert(UU).second)
888 Worklist.push_back(UU);
889 }
Nick Lewycky5361b842011-01-02 19:16:44 +0000890 }
Nick Lewycky00959372010-09-05 08:22:49 +0000891 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000892 }
Nick Lewycky00959372010-09-05 08:22:49 +0000893}