blob: 4c51cd131a1015d654e1de9f8b5232b390d097af [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.
Fangrui Songf78650a2018-07-30 19:41:25 +000030//
JF Bastien5e4303d2015-08-15 01:18:18 +000031// 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
Eugene Zelenkof27d1612017-10-19 21:21:30 +000092#include "llvm/ADT/ArrayRef.h"
Florian Hahna1cc8482018-06-12 11:16:56 +000093#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000094#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000095#include "llvm/ADT/Statistic.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +000096#include "llvm/IR/Argument.h"
97#include "llvm/IR/Attributes.h"
98#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000099#include "llvm/IR/CallSite.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000100#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000101#include "llvm/IR/Constants.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000102#include "llvm/IR/DebugInfoMetadata.h"
103#include "llvm/IR/DebugLoc.h"
104#include "llvm/IR/DerivedTypes.h"
105#include "llvm/IR/Function.h"
106#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000107#include "llvm/IR/IRBuilder.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000108#include "llvm/IR/InstrTypes.h"
109#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000110#include "llvm/IR/Instructions.h"
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000111#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000112#include "llvm/IR/Module.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000113#include "llvm/IR/Type.h"
114#include "llvm/IR/Use.h"
115#include "llvm/IR/User.h"
116#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +0000117#include "llvm/IR/ValueHandle.h"
JF Bastien057292a2015-08-21 23:27:24 +0000118#include "llvm/IR/ValueMap.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000119#include "llvm/Pass.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000120#include "llvm/Support/Casting.h"
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000121#include "llvm/Support/CommandLine.h"
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000122#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +0000123#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +0000124#include "llvm/Transforms/IPO.h"
Erik Eckstein4d6fb722016-11-11 21:15:13 +0000125#include "llvm/Transforms/Utils/FunctionComparator.h"
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000126#include <algorithm>
127#include <cassert>
128#include <iterator>
129#include <set>
130#include <utility>
Nick Lewycky68984ed2010-08-31 08:29:37 +0000131#include <vector>
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000132
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000133using namespace llvm;
134
Chandler Carruth964daaa2014-04-22 02:55:47 +0000135#define DEBUG_TYPE "mergefunc"
136
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000137STATISTIC(NumFunctionsMerged, "Number of functions merged");
Nick Lewycky71972d42010-09-07 01:42:10 +0000138STATISTIC(NumThunksWritten, "Number of thunks generated");
139STATISTIC(NumDoubleWeak, "Number of new functions created");
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000140
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000141static cl::opt<unsigned> NumFunctionsForSanityCheck(
142 "mergefunc-sanity",
143 cl::desc("How many functions in module could be used for "
144 "MergeFunctions pass sanity check. "
145 "'0' disables this check. Works only with '-debug' key."),
146 cl::init(0), cl::Hidden);
147
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000148// Under option -mergefunc-preserve-debug-info we:
149// - Do not create a new function for a thunk.
150// - Retain the debug info for a thunk's parameters (and associated
151// instructions for the debug info) from the entry block.
152// Note: -debug will display the algorithm at work.
153// - Create debug-info for the call (to the shared implementation) made by
154// a thunk and its return value.
155// - Erase the rest of the function, retaining the (minimally sized) entry
156// block to create a thunk.
157// - Preserve a thunk's call site to point to the thunk even when both occur
158// within the same translation unit, to aid debugability. Note that this
159// behaviour differs from the underlying -mergefunc implementation which
160// modifies the thunk's call site to point to the shared implementation
161// when both occur within the same translation unit.
162static cl::opt<bool>
163 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
164 cl::init(false),
165 cl::desc("Preserve debug info in thunk when mergefunc "
166 "transformations are made."));
167
Nick Lewyckyf3a07ec2010-09-05 09:00:32 +0000168namespace {
Nick Lewycky00959372010-09-05 08:22:49 +0000169
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000170class FunctionNode {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000171 mutable AssertingVH<Function> F;
JF Bastien5e4303d2015-08-15 01:18:18 +0000172 FunctionComparator::FunctionHash Hash;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000173
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000174public:
JF Bastien5e4303d2015-08-15 01:18:18 +0000175 // Note the hash is recalculated potentially multiple times, but it is cheap.
JF Bastien057292a2015-08-21 23:27:24 +0000176 FunctionNode(Function *F)
177 : F(F), Hash(FunctionComparator::functionHash(*F)) {}
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000178
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000179 Function *getFunc() const { return F; }
JF Bastien057292a2015-08-21 23:27:24 +0000180 FunctionComparator::FunctionHash getHash() const { return Hash; }
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000181
182 /// Replace the reference to the function F by the function G, assuming their
183 /// implementations are equal.
184 void replaceBy(Function *G) const {
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000185 F = G;
186 }
187
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000188 void release() { F = nullptr; }
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000189};
Nick Lewycky564fcca2011-01-28 07:36:21 +0000190
191/// MergeFunctions finds functions which will generate identical machine code,
192/// by considering all pointer types to be equivalent. Once identified,
193/// MergeFunctions will fold them by replacing a call to one to a call to a
194/// bitcast of the other.
Nick Lewycky564fcca2011-01-28 07:36:21 +0000195class MergeFunctions : public ModulePass {
196public:
197 static char ID;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000198
Nick Lewycky564fcca2011-01-28 07:36:21 +0000199 MergeFunctions()
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000200 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)) {
Nick Lewycky564fcca2011-01-28 07:36:21 +0000201 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
202 }
203
Craig Topper3e4c6972014-03-05 09:10:37 +0000204 bool runOnModule(Module &M) override;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000205
206private:
JF Bastien057292a2015-08-21 23:27:24 +0000207 // The function comparison operator is provided here so that FunctionNodes do
208 // not need to become larger with another pointer.
209 class FunctionNodeCmp {
210 GlobalNumberState* GlobalNumbers;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000211
JF Bastien057292a2015-08-21 23:27:24 +0000212 public:
213 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000214
JF Bastien057292a2015-08-21 23:27:24 +0000215 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
216 // Order first by hashes, then full function comparison.
217 if (LHS.getHash() != RHS.getHash())
218 return LHS.getHash() < RHS.getHash();
219 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
220 return FCmp.compare() == -1;
221 }
222 };
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000223 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
JF Bastien057292a2015-08-21 23:27:24 +0000224
225 GlobalNumberState GlobalNumbers;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000226
227 /// A work queue of functions that may have been modified and should be
228 /// analyzed again.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000229 std::vector<WeakTrackingVH> Deferred;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000230
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000231#ifndef NDEBUG
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000232 /// Checks the rules of order relation introduced among functions set.
233 /// Returns true, if sanity check has been passed, and false if failed.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000234 bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist);
Davide Italianob6681e22017-04-28 19:39:45 +0000235#endif
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000236
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000237 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
Nick Lewycky564fcca2011-01-28 07:36:21 +0000238 /// equal to one that's already present.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000239 bool insert(Function *NewFunction);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000240
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000241 /// Remove a Function from the FnTree and queue it up for a second sweep of
Nick Lewycky564fcca2011-01-28 07:36:21 +0000242 /// analysis.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000243 void remove(Function *F);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000244
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000245 /// Find the functions that use this Value and remove them from FnTree and
Nick Lewycky564fcca2011-01-28 07:36:21 +0000246 /// queue the functions.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000247 void removeUsers(Value *V);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000248
249 /// Replace all direct calls of Old with calls of New. Will bitcast New if
250 /// necessary to make types match.
251 void replaceDirectCallers(Function *Old, Function *New);
252
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000253 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
254 /// be converted into a thunk. In either case, it should never be visited
255 /// again.
256 void mergeTwoFunctions(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000257
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000258 /// Fill PDIUnrelatedWL with instructions from the entry block that are
259 /// unrelated to parameter related debug info.
260 void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
261 std::vector<Instruction *> &PDIUnrelatedWL);
262
263 /// Erase the rest of the CFG (i.e. barring the entry block).
264 void eraseTail(Function *G);
265
266 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
267 /// parameter debug info, from the entry block.
268 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
269
270 /// Replace G with a simple tail call to bitcast(F). Also (unless
271 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
272 /// delete G.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000273 void writeThunk(Function *F, Function *G);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000274
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000275 /// Replace function F with function G in the function tree.
JF Bastien3a4ad612015-09-02 23:55:23 +0000276 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000277
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000278 /// The set of all distinct functions. Use the insert() and remove() methods
JF Bastien3a4ad612015-09-02 23:55:23 +0000279 /// to modify it. The map allows efficient lookup and deferring of Functions.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000280 FnTreeType FnTree;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000281
JF Bastien3a4ad612015-09-02 23:55:23 +0000282 // Map functions to the iterators of the FunctionNode which contains them
283 // in the FnTree. This must be updated carefully whenever the FnTree is
284 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
285 // dangling iterators into FnTree. The invariant that preserves this is that
286 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
whitequark73cb9782018-11-08 03:58:01 +0000287 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000288};
289
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000290} // end anonymous namespace
Nick Lewycky564fcca2011-01-28 07:36:21 +0000291
292char MergeFunctions::ID = 0;
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000293
Nick Lewycky564fcca2011-01-28 07:36:21 +0000294INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
295
296ModulePass *llvm::createMergeFunctionsPass() {
297 return new MergeFunctions();
298}
299
Davide Italianob6681e22017-04-28 19:39:45 +0000300#ifndef NDEBUG
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000301bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) {
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000302 if (const unsigned Max = NumFunctionsForSanityCheck) {
303 unsigned TripleNumber = 0;
304 bool Valid = true;
305
306 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
307
308 unsigned i = 0;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000309 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
310 E = Worklist.end();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000311 I != E && i < Max; ++I, ++i) {
312 unsigned j = i;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000313 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
314 ++J, ++j) {
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000315 Function *F1 = cast<Function>(*I);
316 Function *F2 = cast<Function>(*J);
JF Bastien057292a2015-08-21 23:27:24 +0000317 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
318 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000319
320 // If F1 <= F2, then F2 >= F1, otherwise report failure.
321 if (Res1 != -Res2) {
322 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
323 << "\n";
Matthias Braun194ded52017-01-28 06:53:55 +0000324 dbgs() << *F1 << '\n' << *F2 << '\n';
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000325 Valid = false;
326 }
327
328 if (Res1 == 0)
329 continue;
330
331 unsigned k = j;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000332 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000333 ++k, ++K, ++TripleNumber) {
334 if (K == J)
335 continue;
336
337 Function *F3 = cast<Function>(*K);
JF Bastien057292a2015-08-21 23:27:24 +0000338 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
339 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000340
341 bool Transitive = true;
342
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000343 if (Res1 != 0 && Res1 == Res4) {
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000344 // F1 > F2, F2 > F3 => F1 > F3
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000345 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000346 } else if (Res3 != 0 && Res3 == -Res4) {
347 // F1 > F3, F3 > F2 => F1 > F2
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000348 Transitive = Res3 == Res1;
Stepan Dyatkovskiy0b588012014-06-21 19:07:51 +0000349 } else if (Res4 != 0 && -Res3 == Res4) {
350 // F2 > F3, F3 > F1 => F2 > F1
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000351 Transitive = Res4 == -Res1;
352 }
353
354 if (!Transitive) {
355 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
356 << TripleNumber << "\n";
357 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
358 << Res4 << "\n";
Matthias Braun194ded52017-01-28 06:53:55 +0000359 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000360 Valid = false;
361 }
362 }
363 }
364 }
365
366 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
367 return Valid;
368 }
369 return true;
370}
Davide Italianob6681e22017-04-28 19:39:45 +0000371#endif
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000372
Nick Lewycky564fcca2011-01-28 07:36:21 +0000373bool MergeFunctions::runOnModule(Module &M) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000374 if (skipModule(M))
375 return false;
376
Nick Lewycky564fcca2011-01-28 07:36:21 +0000377 bool Changed = false;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000378
JF Bastien5e4303d2015-08-15 01:18:18 +0000379 // All functions in the module, ordered by hash. Functions with a unique
380 // hash value are easily eliminated.
381 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
382 HashedFuncs;
383 for (Function &Func : M) {
384 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
385 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
Fangrui Songf78650a2018-07-30 19:41:25 +0000386 }
Nick Lewycky564fcca2011-01-28 07:36:21 +0000387 }
Nick Lewycky564fcca2011-01-28 07:36:21 +0000388
NAKAMURA Takumi51962752015-08-16 02:41:23 +0000389 std::stable_sort(
390 HashedFuncs.begin(), HashedFuncs.end(),
391 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
392 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
393 return a.first < b.first;
394 });
JF Bastien5e4303d2015-08-15 01:18:18 +0000395
396 auto S = HashedFuncs.begin();
397 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
398 // If the hash value matches the previous value or the next one, we must
399 // consider merging it. Otherwise it is dropped and never considered again.
400 if ((I != S && std::prev(I)->first == I->first) ||
401 (std::next(I) != IE && std::next(I)->first == I->first) ) {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000402 Deferred.push_back(WeakTrackingVH(I->second));
JF Bastien5e4303d2015-08-15 01:18:18 +0000403 }
404 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000405
Nick Lewycky564fcca2011-01-28 07:36:21 +0000406 do {
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000407 std::vector<WeakTrackingVH> Worklist;
Nick Lewycky564fcca2011-01-28 07:36:21 +0000408 Deferred.swap(Worklist);
409
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000410 LLVM_DEBUG(doSanityCheck(Worklist));
Stepan Dyatkovskiya77f3d82014-06-21 18:58:11 +0000411
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000412 LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
413 LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +0000414
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000415 // Insert functions and merge them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000416 for (WeakTrackingVH &I : Worklist) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000417 if (!I)
418 continue;
419 Function *F = cast<Function>(I);
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000420 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000421 Changed |= insert(F);
Nick Lewycky564fcca2011-01-28 07:36:21 +0000422 }
423 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000424 LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
Nick Lewycky564fcca2011-01-28 07:36:21 +0000425 } while (!Deferred.empty());
426
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000427 FnTree.clear();
whitequark73cb9782018-11-08 03:58:01 +0000428 FNodesInTree.clear();
Arnold Schwaighofer0591c5d2015-10-05 17:26:36 +0000429 GlobalNumbers.clear();
Nick Lewycky564fcca2011-01-28 07:36:21 +0000430
431 return Changed;
432}
433
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000434// Replace direct callers of Old with New.
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000435void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
436 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000437 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
438 Use *U = &*UI;
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000439 ++UI;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000440 CallSite CS(U->getUser());
441 if (CS && CS.isCallee(U)) {
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000442 // Transfer the called function's attributes to the call site. Due to the
JF Bastienfa946232015-09-10 18:08:35 +0000443 // bitcast we will 'lose' ABI changing attributes because the 'called
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000444 // function' is no longer a Function* but the bitcast. Code that looks up
445 // the attributes from the called function will fail.
JF Bastienfa946232015-09-10 18:08:35 +0000446
447 // FIXME: This is not actually true, at least not anymore. The callsite
448 // will always have the same ABI affecting attributes as the callee,
449 // because otherwise the original input has UB. Note that Old and New
450 // always have matching ABI, so no attributes need to be changed.
451 // Transferring other attributes may help other optimizations, but that
452 // should be done uniformly and not in this ad-hoc way.
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000453 auto &Context = New->getContext();
Reid Klecknerf021fab2017-04-13 23:12:13 +0000454 auto NewPAL = New->getAttributes();
455 SmallVector<AttributeSet, 4> NewArgAttrs;
456 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++)
457 NewArgAttrs.push_back(NewPAL.getParamAttributes(argIdx));
458 // Don't transfer attributes from the function to the callee. Function
459 // attributes typically aren't relevant to the calling convention or ABI.
460 CS.setAttributes(AttributeList::get(Context, /*FnAttrs=*/AttributeSet(),
461 NewPAL.getRetAttributes(),
462 NewArgAttrs));
Arnold Schwaighofer36512332015-07-21 17:07:07 +0000463
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000464 remove(CS.getInstruction()->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000465 U->set(BitcastNew);
Nick Lewyckyf1cec162011-01-25 08:56:50 +0000466 }
467 }
468}
469
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000470// Helper for writeThunk,
471// Selects proper bitcast operation,
Alp Tokercb402912014-01-24 17:20:08 +0000472// but a bit simpler then CastInst::getCastOpcode.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000473static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000474 Type *SrcTy = V->getType();
Carlo Kok307625c2014-04-30 17:53:04 +0000475 if (SrcTy->isStructTy()) {
476 assert(DestTy->isStructTy());
477 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
478 Value *Result = UndefValue::get(DestTy);
479 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
480 Value *Element = createCast(
Craig Toppere1d12942014-08-27 05:25:25 +0000481 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
Carlo Kok307625c2014-04-30 17:53:04 +0000482 DestTy->getStructElementType(I));
483
484 Result =
Craig Toppere1d12942014-08-27 05:25:25 +0000485 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
Carlo Kok307625c2014-04-30 17:53:04 +0000486 }
487 return Result;
488 }
489 assert(!DestTy->isStructTy());
Stepan Dyatkovskiydc2c4b42013-09-17 09:36:11 +0000490 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
491 return Builder.CreateIntToPtr(V, DestTy);
492 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
493 return Builder.CreatePtrToInt(V, DestTy);
494 else
495 return Builder.CreateBitCast(V, DestTy);
496}
497
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000498// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
499// parameter debug info, from the entry block.
500void MergeFunctions::eraseInstsUnrelatedToPDI(
501 std::vector<Instruction *> &PDIUnrelatedWL) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000502 LLVM_DEBUG(
503 dbgs() << " Erasing instructions (in reverse order of appearance in "
504 "entry block) unrelated to parameter debug info from entry "
505 "block: {\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000506 while (!PDIUnrelatedWL.empty()) {
507 Instruction *I = PDIUnrelatedWL.back();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000508 LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
509 LLVM_DEBUG(I->print(dbgs()));
510 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000511 I->eraseFromParent();
512 PDIUnrelatedWL.pop_back();
513 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000514 LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
515 "debug info from entry block. \n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000516}
517
518// Reduce G to its entry block.
519void MergeFunctions::eraseTail(Function *G) {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000520 std::vector<BasicBlock *> WorklistBB;
521 for (Function::iterator BBI = std::next(G->begin()), BBE = G->end();
522 BBI != BBE; ++BBI) {
523 BBI->dropAllReferences();
524 WorklistBB.push_back(&*BBI);
525 }
526 while (!WorklistBB.empty()) {
527 BasicBlock *BB = WorklistBB.back();
528 BB->eraseFromParent();
529 WorklistBB.pop_back();
530 }
531}
532
533// We are interested in the following instructions from the entry block as being
534// related to parameter debug info:
535// - @llvm.dbg.declare
536// - stores from the incoming parameters to locations on the stack-frame
537// - allocas that create these locations on the stack-frame
538// - @llvm.dbg.value
539// - the entry block's terminator
540// The rest are unrelated to debug info for the parameters; fill up
541// PDIUnrelatedWL with such instructions.
542void MergeFunctions::filterInstsUnrelatedToPDI(
543 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000544 std::set<Instruction *> PDIRelated;
545 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
546 BI != BIE; ++BI) {
547 if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000548 LLVM_DEBUG(dbgs() << " Deciding: ");
549 LLVM_DEBUG(BI->print(dbgs()));
550 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000551 DILocalVariable *DILocVar = DVI->getVariable();
552 if (DILocVar->isParameter()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000553 LLVM_DEBUG(dbgs() << " Include (parameter): ");
554 LLVM_DEBUG(BI->print(dbgs()));
555 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000556 PDIRelated.insert(&*BI);
557 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000558 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
559 LLVM_DEBUG(BI->print(dbgs()));
560 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000561 }
562 } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000563 LLVM_DEBUG(dbgs() << " Deciding: ");
564 LLVM_DEBUG(BI->print(dbgs()));
565 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000566 DILocalVariable *DILocVar = DDI->getVariable();
567 if (DILocVar->isParameter()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000568 LLVM_DEBUG(dbgs() << " Parameter: ");
569 LLVM_DEBUG(DILocVar->print(dbgs()));
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000570 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
571 if (AI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000572 LLVM_DEBUG(dbgs() << " Processing alloca users: ");
573 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000574 for (User *U : AI->users()) {
575 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
576 if (Value *Arg = SI->getValueOperand()) {
577 if (dyn_cast<Argument>(Arg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000578 LLVM_DEBUG(dbgs() << " Include: ");
579 LLVM_DEBUG(AI->print(dbgs()));
580 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000581 PDIRelated.insert(AI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000582 LLVM_DEBUG(dbgs() << " Include (parameter): ");
583 LLVM_DEBUG(SI->print(dbgs()));
584 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000585 PDIRelated.insert(SI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000586 LLVM_DEBUG(dbgs() << " Include: ");
587 LLVM_DEBUG(BI->print(dbgs()));
588 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000589 PDIRelated.insert(&*BI);
590 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000591 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
592 LLVM_DEBUG(SI->print(dbgs()));
593 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000594 }
595 }
596 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000597 LLVM_DEBUG(dbgs() << " Defer: ");
598 LLVM_DEBUG(U->print(dbgs()));
599 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000600 }
601 }
602 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000603 LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
604 LLVM_DEBUG(BI->print(dbgs()));
605 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000606 }
607 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000608 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
609 LLVM_DEBUG(BI->print(dbgs()));
610 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000611 }
Chandler Carruth93cf2ea2018-10-18 00:37:37 +0000612 } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000613 LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
614 LLVM_DEBUG(BI->print(dbgs()));
615 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000616 PDIRelated.insert(&*BI);
617 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000618 LLVM_DEBUG(dbgs() << " Defer: ");
619 LLVM_DEBUG(BI->print(dbgs()));
620 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000621 }
622 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000623 LLVM_DEBUG(
624 dbgs()
625 << " Report parameter debug info related/related instructions: {\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000626 for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end();
627 BI != BE; ++BI) {
628
629 Instruction *I = &*BI;
630 if (PDIRelated.find(I) == PDIRelated.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000631 LLVM_DEBUG(dbgs() << " !PDIRelated: ");
632 LLVM_DEBUG(I->print(dbgs()));
633 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000634 PDIUnrelatedWL.push_back(I);
635 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000636 LLVM_DEBUG(dbgs() << " PDIRelated: ");
637 LLVM_DEBUG(I->print(dbgs()));
638 LLVM_DEBUG(dbgs() << "\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000639 }
640 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000641 LLVM_DEBUG(dbgs() << " }\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000642}
643
whitequark8f0ab252018-05-15 11:31:07 +0000644// Don't merge tiny functions using a thunk, since it can just end up
645// making the function larger.
646static bool isThunkProfitable(Function * F) {
647 if (F->size() == 1) {
648 if (F->front().size() <= 2) {
Nicola Zaghen03d0b912018-05-23 15:09:29 +0000649 LLVM_DEBUG(dbgs() << "isThunkProfitable: " << F->getName()
650 << " is too small to bother creating a thunk for\n");
whitequark8f0ab252018-05-15 11:31:07 +0000651 return false;
652 }
653 }
654 return true;
655}
656
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000657// Replace G with a simple tail call to bitcast(F). Also (unless
658// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
659// delete G. Under MergeFunctionsPDI, we use G itself for creating
660// the thunk as we preserve the debug info (and associated instructions)
661// from G's entry block pertaining to G's incoming arguments which are
662// passed on as corresponding arguments in the call that G makes to F.
663// For better debugability, under MergeFunctionsPDI, we do not modify G's
664// call sites to point to F even when within the same translation unit.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000665void MergeFunctions::writeThunk(Function *F, Function *G) {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000666 BasicBlock *GEntryBlock = nullptr;
667 std::vector<Instruction *> PDIUnrelatedWL;
668 BasicBlock *BB = nullptr;
669 Function *NewG = nullptr;
670 if (MergeFunctionsPDI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000671 LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
672 "function as thunk; retain original: "
673 << G->getName() << "()\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000674 GEntryBlock = &G->getEntryBlock();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000675 LLVM_DEBUG(
676 dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
677 "debug info for "
678 << G->getName() << "() {\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000679 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
680 GEntryBlock->getTerminator()->eraseFromParent();
681 BB = GEntryBlock;
682 } else {
683 NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
684 G->getParent());
685 BB = BasicBlock::Create(F->getContext(), "", NewG);
686 }
Nick Lewyckye04dc222009-06-12 08:04:51 +0000687
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000688 IRBuilder<> Builder(BB);
689 Function *H = MergeFunctionsPDI ? G : NewG;
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000690 SmallVector<Value *, 16> Args;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000691 unsigned i = 0;
Chris Lattner229907c2011-07-18 04:54:35 +0000692 FunctionType *FFTy = F->getFunctionType();
Eugene Zelenkof27d1612017-10-19 21:21:30 +0000693 for (Argument &AI : H->args()) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000694 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
Nick Lewyckye04dc222009-06-12 08:04:51 +0000695 ++i;
696 }
697
Jay Foad5bd375a2011-07-15 08:37:34 +0000698 CallInst *CI = Builder.CreateCall(F, Args);
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000699 ReturnInst *RI = nullptr;
Nick Lewyckye04dc222009-06-12 08:04:51 +0000700 CI->setTailCall();
Nick Lewyckyd5bf51f2009-06-12 16:04:00 +0000701 CI->setCallingConv(F->getCallingConv());
JF Bastienfa946232015-09-10 18:08:35 +0000702 CI->setAttributes(F->getAttributes());
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000703 if (H->getReturnType()->isVoidTy()) {
704 RI = Builder.CreateRetVoid();
Nick Lewyckye04dc222009-06-12 08:04:51 +0000705 } else {
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000706 RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
Nick Lewyckye04dc222009-06-12 08:04:51 +0000707 }
708
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000709 if (MergeFunctionsPDI) {
710 DISubprogram *DIS = G->getSubprogram();
711 if (DIS) {
712 DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
713 DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
714 CI->setDebugLoc(CIDbgLoc);
715 RI->setDebugLoc(RIDbgLoc);
716 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000717 LLVM_DEBUG(
718 dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
719 << G->getName() << "()\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000720 }
721 eraseTail(G);
722 eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000723 LLVM_DEBUG(
724 dbgs() << "} // End of parameter related debug info filtering for: "
725 << G->getName() << "()\n");
Anmol P. Paralkar910dc8d2017-01-21 02:02:56 +0000726 } 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
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000734 LLVM_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// Merge two equivalent functions. Upon completion, Function G is deleted.
739void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000740 if (F->isInterposable()) {
741 assert(G->isInterposable());
Nick Lewyckyd3c6dfe2010-05-13 05:48:45 +0000742
whitequark8f0ab252018-05-15 11:31:07 +0000743 if (!isThunkProfitable(F)) {
744 return;
745 }
746
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000747 // Make them both thunks to the same internal function.
748 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
749 F->getParent());
750 H->copyAttributesFrom(F);
751 H->takeName(F);
752 removeUsers(F);
753 F->replaceAllUsesWith(H);
754
755 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
756
whitequark9e8197a2017-07-27 19:36:13 +0000757 writeThunk(F, G);
758 writeThunk(F, H);
Nick Lewycky71972d42010-09-07 01:42:10 +0000759
Arnold Schwaighofer7e226272015-06-09 18:19:17 +0000760 F->setAlignment(MaxAlignment);
761 F->setLinkage(GlobalValue::PrivateLinkage);
Nick Lewycky71972d42010-09-07 01:42:10 +0000762 ++NumDoubleWeak;
whitequark8f0ab252018-05-15 11:31:07 +0000763 ++NumFunctionsMerged;
Nick Lewyckyf216f69a2010-08-06 07:21:30 +0000764 } else {
whitequark8f0ab252018-05-15 11:31:07 +0000765 // For better debugability, under MergeFunctionsPDI, we do not modify G's
766 // call sites to point to F even when within the same translation unit.
767 if (!G->isInterposable() && !MergeFunctionsPDI) {
768 if (G->hasGlobalUnnamedAddr()) {
769 // G might have been a key in our GlobalNumberState, and it's illegal
770 // to replace a key in ValueMap<GlobalValue *> with a non-global.
771 GlobalNumbers.erase(G);
772 // If G's address is not significant, replace it entirely.
773 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
whitequark3580ac62018-11-08 03:57:55 +0000774 removeUsers(G);
whitequark8f0ab252018-05-15 11:31:07 +0000775 G->replaceAllUsesWith(BitcastF);
776 } else {
777 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
778 // above).
779 replaceDirectCallers(G, F);
780 }
781 }
Nick Lewycky3c6d34a2008-11-02 16:46:26 +0000782
whitequark8f0ab252018-05-15 11:31:07 +0000783 // If G was internal then we may have replaced all uses of G with F. If so,
784 // stop here and delete G. There's no need for a thunk. (See note on
785 // MergeFunctionsPDI above).
786 if (G->hasLocalLinkage() && G->use_empty() && !MergeFunctionsPDI) {
787 G->eraseFromParent();
788 ++NumFunctionsMerged;
789 return;
790 }
791
792 if (!isThunkProfitable(F)) {
793 return;
794 }
795
796 writeThunk(F, G);
797 ++NumFunctionsMerged;
798 }
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000799}
800
JF Bastien3a4ad612015-09-02 23:55:23 +0000801/// Replace function F by function G.
802void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000803 Function *G) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000804 Function *F = FN.getFunc();
JF Bastien057292a2015-08-21 23:27:24 +0000805 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
806 "The two functions must be equal");
Fangrui Songf78650a2018-07-30 19:41:25 +0000807
JF Bastien3a4ad612015-09-02 23:55:23 +0000808 auto I = FNodesInTree.find(F);
809 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
810 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
Fangrui Songf78650a2018-07-30 19:41:25 +0000811
JF Bastien3a4ad612015-09-02 23:55:23 +0000812 FnTreeType::iterator IterToFNInFnTree = I->second;
813 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
814 // Remove F -> FN and insert G -> FN
815 FNodesInTree.erase(I);
816 FNodesInTree.insert({G, IterToFNInFnTree});
817 // Replace F with G in FN, which is stored inside the FnTree.
818 FN.replaceBy(G);
Arnold Schwaighofer0302da62015-06-09 00:03:29 +0000819}
820
whitequark73cb9782018-11-08 03:58:01 +0000821// Ordering for functions that are equal under FunctionComparator
822static bool isFuncOrderCorrect(const Function *F, const Function *G) {
823 if (F->isInterposable() != G->isInterposable()) {
824 // Strong before weak, because the weak function may call the strong
825 // one, but not the other way around.
826 return !F->isInterposable();
827 }
828 if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
829 // External before local, because we definitely have to keep the external
830 // function, but may be able to drop the local one.
831 return !F->hasLocalLinkage();
832 }
833 // Impose a total order (by name) on the replacement of functions. This is
834 // important when operating on more than one module independently to prevent
835 // cycles of thunks calling each other when the modules are linked together.
836 return F->getName() <= G->getName();
837}
838
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000839// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000840// that was already inserted.
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000841bool MergeFunctions::insert(Function *NewFunction) {
842 std::pair<FnTreeType::iterator, bool> Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000843 FnTree.insert(FunctionNode(NewFunction));
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000844
Nick Lewycky292e78c2011-02-09 06:32:02 +0000845 if (Result.second) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000846 assert(FNodesInTree.count(NewFunction) == 0);
847 FNodesInTree.insert({NewFunction, Result.first});
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000848 LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
849 << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +0000850 return false;
Nick Lewycky292e78c2011-02-09 06:32:02 +0000851 }
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000852
Stepan Dyatkovskiyfe134cd2014-09-10 10:08:25 +0000853 const FunctionNode &OldF = *Result.first;
Nick Lewycky00959372010-09-05 08:22:49 +0000854
whitequark73cb9782018-11-08 03:58:01 +0000855 if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
Erik Eckstein0c48dd82016-05-31 17:20:23 +0000856 // Swap the two functions.
857 Function *F = OldF.getFunc();
858 replaceFunctionInTree(*Result.first, NewFunction);
859 NewFunction = F;
860 assert(OldF.getFunc() != F && "Must have swapped the functions.");
861 }
Nick Lewycky00959372010-09-05 08:22:49 +0000862
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000863 LLVM_DEBUG(dbgs() << " " << OldF.getFunc()->getName()
864 << " == " << NewFunction->getName() << '\n');
Nick Lewycky00959372010-09-05 08:22:49 +0000865
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000866 Function *DeleteF = NewFunction;
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000867 mergeTwoFunctions(OldF.getFunc(), DeleteF);
Nick Lewycky00959372010-09-05 08:22:49 +0000868 return true;
Nick Lewyckyfbd27572010-08-08 05:04:23 +0000869}
Nick Lewyckyd01d42e2008-11-02 05:52:50 +0000870
Stepan Dyatkovskiyf4af8552014-06-21 20:54:36 +0000871// Remove a function from FnTree. If it was already in FnTree, add
872// it to Deferred so that we'll look at it in the next round.
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000873void MergeFunctions::remove(Function *F) {
JF Bastien3a4ad612015-09-02 23:55:23 +0000874 auto I = FNodesInTree.find(F);
875 if (I != FNodesInTree.end()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000876 LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
JF Bastien3a4ad612015-09-02 23:55:23 +0000877 FnTree.erase(I->second);
878 // I->second has been invalidated, remove it from the FNodesInTree map to
879 // preserve the invariant.
880 FNodesInTree.erase(I);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000881 Deferred.emplace_back(F);
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000882 }
Nick Lewycky4e250c82011-01-02 02:46:33 +0000883}
Nick Lewycky00959372010-09-05 08:22:49 +0000884
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000885// For each instruction used by the value, remove() the function that contains
886// the instruction. This should happen right before a call to RAUW.
887void MergeFunctions::removeUsers(Value *V) {
Nick Lewycky5361b842011-01-02 19:16:44 +0000888 std::vector<Value *> Worklist;
889 Worklist.push_back(V);
Florian Hahna1cc8482018-06-12 11:16:56 +0000890 SmallPtrSet<Value*, 8> Visited;
JF Bastien7289f732015-07-15 21:51:33 +0000891 Visited.insert(V);
Nick Lewycky5361b842011-01-02 19:16:44 +0000892 while (!Worklist.empty()) {
893 Value *V = Worklist.back();
894 Worklist.pop_back();
895
Chandler Carruthcdf47882014-03-09 03:16:01 +0000896 for (User *U : V->users()) {
897 if (Instruction *I = dyn_cast<Instruction>(U)) {
Nick Lewyckycfb284c2011-01-28 08:43:14 +0000898 remove(I->getParent()->getParent());
Chandler Carruthcdf47882014-03-09 03:16:01 +0000899 } else if (isa<GlobalValue>(U)) {
Nick Lewycky540f9532011-01-15 10:16:23 +0000900 // do nothing
Chandler Carruthcdf47882014-03-09 03:16:01 +0000901 } else if (Constant *C = dyn_cast<Constant>(U)) {
JF Bastien7289f732015-07-15 21:51:33 +0000902 for (User *UU : C->users()) {
903 if (!Visited.insert(UU).second)
904 Worklist.push_back(UU);
905 }
Nick Lewycky5361b842011-01-02 19:16:44 +0000906 }
Nick Lewycky00959372010-09-05 08:22:49 +0000907 }
Nick Lewycky0464d1d2010-08-31 05:53:05 +0000908 }
Nick Lewycky00959372010-09-05 08:22:49 +0000909}