Bug Summary

File:lib/Transforms/IPO/MergeFunctions.cpp
Warning:line 706, column 23
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MergeFunctions.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/lib/Transforms/IPO -I /build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/lib/Transforms/IPO -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp -faddrsig
1//===- 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//
12// 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).
22//
23// 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.
30//
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.
38//
39// 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.
42//
43//===----------------------------------------------------------------------===//
44//
45// Future work:
46//
47// * 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
51// and call, this is irrelevant, and we'd like to fold such functions.
52//
53// * be smarter about bitcasts.
54//
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
58// other doesn't. We should learn to look through bitcasts.
59//
60// * 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//
90//===----------------------------------------------------------------------===//
91
92#include "llvm/ADT/ArrayRef.h"
93#include "llvm/ADT/SmallPtrSet.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/Statistic.h"
96#include "llvm/IR/Argument.h"
97#include "llvm/IR/Attributes.h"
98#include "llvm/IR/BasicBlock.h"
99#include "llvm/IR/CallSite.h"
100#include "llvm/IR/Constant.h"
101#include "llvm/IR/Constants.h"
102#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"
107#include "llvm/IR/IRBuilder.h"
108#include "llvm/IR/InstrTypes.h"
109#include "llvm/IR/Instruction.h"
110#include "llvm/IR/Instructions.h"
111#include "llvm/IR/IntrinsicInst.h"
112#include "llvm/IR/Module.h"
113#include "llvm/IR/Type.h"
114#include "llvm/IR/Use.h"
115#include "llvm/IR/User.h"
116#include "llvm/IR/Value.h"
117#include "llvm/IR/ValueHandle.h"
118#include "llvm/IR/ValueMap.h"
119#include "llvm/Pass.h"
120#include "llvm/Support/Casting.h"
121#include "llvm/Support/CommandLine.h"
122#include "llvm/Support/Debug.h"
123#include "llvm/Support/raw_ostream.h"
124#include "llvm/Transforms/IPO.h"
125#include "llvm/Transforms/Utils/FunctionComparator.h"
126#include <algorithm>
127#include <cassert>
128#include <iterator>
129#include <set>
130#include <utility>
131#include <vector>
132
133using namespace llvm;
134
135#define DEBUG_TYPE"mergefunc" "mergefunc"
136
137STATISTIC(NumFunctionsMerged, "Number of functions merged")static llvm::Statistic NumFunctionsMerged = {"mergefunc", "NumFunctionsMerged"
, "Number of functions merged", {0}, {false}}
;
138STATISTIC(NumThunksWritten, "Number of thunks generated")static llvm::Statistic NumThunksWritten = {"mergefunc", "NumThunksWritten"
, "Number of thunks generated", {0}, {false}}
;
139STATISTIC(NumAliasesWritten, "Number of aliases generated")static llvm::Statistic NumAliasesWritten = {"mergefunc", "NumAliasesWritten"
, "Number of aliases generated", {0}, {false}}
;
140STATISTIC(NumDoubleWeak, "Number of new functions created")static llvm::Statistic NumDoubleWeak = {"mergefunc", "NumDoubleWeak"
, "Number of new functions created", {0}, {false}}
;
141
142static cl::opt<unsigned> NumFunctionsForSanityCheck(
143 "mergefunc-sanity",
144 cl::desc("How many functions in module could be used for "
145 "MergeFunctions pass sanity check. "
146 "'0' disables this check. Works only with '-debug' key."),
147 cl::init(0), cl::Hidden);
148
149// Under option -mergefunc-preserve-debug-info we:
150// - Do not create a new function for a thunk.
151// - Retain the debug info for a thunk's parameters (and associated
152// instructions for the debug info) from the entry block.
153// Note: -debug will display the algorithm at work.
154// - Create debug-info for the call (to the shared implementation) made by
155// a thunk and its return value.
156// - Erase the rest of the function, retaining the (minimally sized) entry
157// block to create a thunk.
158// - Preserve a thunk's call site to point to the thunk even when both occur
159// within the same translation unit, to aid debugability. Note that this
160// behaviour differs from the underlying -mergefunc implementation which
161// modifies the thunk's call site to point to the shared implementation
162// when both occur within the same translation unit.
163static cl::opt<bool>
164 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
165 cl::init(false),
166 cl::desc("Preserve debug info in thunk when mergefunc "
167 "transformations are made."));
168
169static cl::opt<bool>
170 MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
171 cl::init(false),
172 cl::desc("Allow mergefunc to create aliases"));
173
174namespace {
175
176class FunctionNode {
177 mutable AssertingVH<Function> F;
178 FunctionComparator::FunctionHash Hash;
179
180public:
181 // Note the hash is recalculated potentially multiple times, but it is cheap.
182 FunctionNode(Function *F)
183 : F(F), Hash(FunctionComparator::functionHash(*F)) {}
184
185 Function *getFunc() const { return F; }
186 FunctionComparator::FunctionHash getHash() const { return Hash; }
187
188 /// Replace the reference to the function F by the function G, assuming their
189 /// implementations are equal.
190 void replaceBy(Function *G) const {
191 F = G;
192 }
193
194 void release() { F = nullptr; }
195};
196
197/// MergeFunctions finds functions which will generate identical machine code,
198/// by considering all pointer types to be equivalent. Once identified,
199/// MergeFunctions will fold them by replacing a call to one to a call to a
200/// bitcast of the other.
201class MergeFunctions : public ModulePass {
202public:
203 static char ID;
204
205 MergeFunctions()
206 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)) {
207 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
208 }
209
210 bool runOnModule(Module &M) override;
211
212private:
213 // The function comparison operator is provided here so that FunctionNodes do
214 // not need to become larger with another pointer.
215 class FunctionNodeCmp {
216 GlobalNumberState* GlobalNumbers;
217
218 public:
219 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
220
221 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
222 // Order first by hashes, then full function comparison.
223 if (LHS.getHash() != RHS.getHash())
224 return LHS.getHash() < RHS.getHash();
225 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
226 return FCmp.compare() == -1;
227 }
228 };
229 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
230
231 GlobalNumberState GlobalNumbers;
232
233 /// A work queue of functions that may have been modified and should be
234 /// analyzed again.
235 std::vector<WeakTrackingVH> Deferred;
236
237#ifndef NDEBUG
238 /// Checks the rules of order relation introduced among functions set.
239 /// Returns true, if sanity check has been passed, and false if failed.
240 bool doSanityCheck(std::vector<WeakTrackingVH> &Worklist);
241#endif
242
243 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
244 /// equal to one that's already present.
245 bool insert(Function *NewFunction);
246
247 /// Remove a Function from the FnTree and queue it up for a second sweep of
248 /// analysis.
249 void remove(Function *F);
250
251 /// Find the functions that use this Value and remove them from FnTree and
252 /// queue the functions.
253 void removeUsers(Value *V);
254
255 /// Replace all direct calls of Old with calls of New. Will bitcast New if
256 /// necessary to make types match.
257 void replaceDirectCallers(Function *Old, Function *New);
258
259 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
260 /// be converted into a thunk. In either case, it should never be visited
261 /// again.
262 void mergeTwoFunctions(Function *F, Function *G);
263
264 /// Fill PDIUnrelatedWL with instructions from the entry block that are
265 /// unrelated to parameter related debug info.
266 void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
267 std::vector<Instruction *> &PDIUnrelatedWL);
268
269 /// Erase the rest of the CFG (i.e. barring the entry block).
270 void eraseTail(Function *G);
271
272 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
273 /// parameter debug info, from the entry block.
274 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
275
276 /// Replace G with a simple tail call to bitcast(F). Also (unless
277 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
278 /// delete G.
279 void writeThunk(Function *F, Function *G);
280
281 // Replace G with an alias to F (deleting function G)
282 void writeAlias(Function *F, Function *G);
283
284 // Replace G with an alias to F if possible, or a thunk to F if
285 // profitable. Returns false if neither is the case.
286 bool writeThunkOrAlias(Function *F, Function *G);
287
288 /// Replace function F with function G in the function tree.
289 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
290
291 /// The set of all distinct functions. Use the insert() and remove() methods
292 /// to modify it. The map allows efficient lookup and deferring of Functions.
293 FnTreeType FnTree;
294
295 // Map functions to the iterators of the FunctionNode which contains them
296 // in the FnTree. This must be updated carefully whenever the FnTree is
297 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
298 // dangling iterators into FnTree. The invariant that preserves this is that
299 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
300 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
301};
302
303} // end anonymous namespace
304
305char MergeFunctions::ID = 0;
306
307INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)static void *initializeMergeFunctionsPassOnce(PassRegistry &
Registry) { PassInfo *PI = new PassInfo( "Merge Functions", "mergefunc"
, &MergeFunctions::ID, PassInfo::NormalCtor_t(callDefaultCtor
<MergeFunctions>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeMergeFunctionsPassFlag
; void llvm::initializeMergeFunctionsPass(PassRegistry &Registry
) { llvm::call_once(InitializeMergeFunctionsPassFlag, initializeMergeFunctionsPassOnce
, std::ref(Registry)); }
308
309ModulePass *llvm::createMergeFunctionsPass() {
310 return new MergeFunctions();
311}
312
313#ifndef NDEBUG
314bool MergeFunctions::doSanityCheck(std::vector<WeakTrackingVH> &Worklist) {
315 if (const unsigned Max = NumFunctionsForSanityCheck) {
316 unsigned TripleNumber = 0;
317 bool Valid = true;
318
319 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
320
321 unsigned i = 0;
322 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
323 E = Worklist.end();
324 I != E && i < Max; ++I, ++i) {
325 unsigned j = i;
326 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
327 ++J, ++j) {
328 Function *F1 = cast<Function>(*I);
329 Function *F2 = cast<Function>(*J);
330 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
331 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
332
333 // If F1 <= F2, then F2 >= F1, otherwise report failure.
334 if (Res1 != -Res2) {
335 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
336 << "\n";
337 dbgs() << *F1 << '\n' << *F2 << '\n';
338 Valid = false;
339 }
340
341 if (Res1 == 0)
342 continue;
343
344 unsigned k = j;
345 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
346 ++k, ++K, ++TripleNumber) {
347 if (K == J)
348 continue;
349
350 Function *F3 = cast<Function>(*K);
351 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
352 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
353
354 bool Transitive = true;
355
356 if (Res1 != 0 && Res1 == Res4) {
357 // F1 > F2, F2 > F3 => F1 > F3
358 Transitive = Res3 == Res1;
359 } else if (Res3 != 0 && Res3 == -Res4) {
360 // F1 > F3, F3 > F2 => F1 > F2
361 Transitive = Res3 == Res1;
362 } else if (Res4 != 0 && -Res3 == Res4) {
363 // F2 > F3, F3 > F1 => F2 > F1
364 Transitive = Res4 == -Res1;
365 }
366
367 if (!Transitive) {
368 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
369 << TripleNumber << "\n";
370 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
371 << Res4 << "\n";
372 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
373 Valid = false;
374 }
375 }
376 }
377 }
378
379 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
380 return Valid;
381 }
382 return true;
383}
384#endif
385
386bool MergeFunctions::runOnModule(Module &M) {
387 if (skipModule(M))
1
Assuming the condition is false
2
Taking false branch
388 return false;
389
390 bool Changed = false;
391
392 // All functions in the module, ordered by hash. Functions with a unique
393 // hash value are easily eliminated.
394 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
395 HashedFuncs;
396 for (Function &Func : M) {
397 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
398 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
399 }
400 }
401
402 std::stable_sort(
403 HashedFuncs.begin(), HashedFuncs.end(),
404 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
405 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
406 return a.first < b.first;
407 });
408
409 auto S = HashedFuncs.begin();
410 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
3
Loop condition is false. Execution continues on line 420
411 // If the hash value matches the previous value or the next one, we must
412 // consider merging it. Otherwise it is dropped and never considered again.
413 if ((I != S && std::prev(I)->first == I->first) ||
414 (std::next(I) != IE && std::next(I)->first == I->first) ) {
415 Deferred.push_back(WeakTrackingVH(I->second));
416 }
417 }
418
419 do {
420 std::vector<WeakTrackingVH> Worklist;
421 Deferred.swap(Worklist);
422
423 LLVM_DEBUG(doSanityCheck(Worklist))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { doSanityCheck(Worklist); } } while (false)
;
4
Assuming 'DebugFlag' is 0
5
Loop condition is false. Exiting loop
424
425 LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "size of module: " << M
.size() << '\n'; } } while (false)
;
6
Loop condition is false. Exiting loop
426 LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "size of worklist: " <<
Worklist.size() << '\n'; } } while (false)
;
7
Loop condition is false. Exiting loop
427
428 // Insert functions and merge them.
429 for (WeakTrackingVH &I : Worklist) {
430 if (!I)
8
Assuming the condition is false
9
Taking false branch
431 continue;
432 Function *F = cast<Function>(I);
433 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
10
Assuming the condition is true
11
Taking true branch
434 Changed |= insert(F);
12
Calling 'MergeFunctions::insert'
435 }
436 }
437 LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "size of FnTree: " << FnTree
.size() << '\n'; } } while (false)
;
438 } while (!Deferred.empty());
439
440 FnTree.clear();
441 FNodesInTree.clear();
442 GlobalNumbers.clear();
443
444 return Changed;
445}
446
447// Replace direct callers of Old with New.
448void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
449 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
450 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
451 Use *U = &*UI;
452 ++UI;
453 CallSite CS(U->getUser());
454 if (CS && CS.isCallee(U)) {
455 // Transfer the called function's attributes to the call site. Due to the
456 // bitcast we will 'lose' ABI changing attributes because the 'called
457 // function' is no longer a Function* but the bitcast. Code that looks up
458 // the attributes from the called function will fail.
459
460 // FIXME: This is not actually true, at least not anymore. The callsite
461 // will always have the same ABI affecting attributes as the callee,
462 // because otherwise the original input has UB. Note that Old and New
463 // always have matching ABI, so no attributes need to be changed.
464 // Transferring other attributes may help other optimizations, but that
465 // should be done uniformly and not in this ad-hoc way.
466 auto &Context = New->getContext();
467 auto NewPAL = New->getAttributes();
468 SmallVector<AttributeSet, 4> NewArgAttrs;
469 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++)
470 NewArgAttrs.push_back(NewPAL.getParamAttributes(argIdx));
471 // Don't transfer attributes from the function to the callee. Function
472 // attributes typically aren't relevant to the calling convention or ABI.
473 CS.setAttributes(AttributeList::get(Context, /*FnAttrs=*/AttributeSet(),
474 NewPAL.getRetAttributes(),
475 NewArgAttrs));
476
477 remove(CS.getInstruction()->getParent()->getParent());
478 U->set(BitcastNew);
479 }
480 }
481}
482
483// Helper for writeThunk,
484// Selects proper bitcast operation,
485// but a bit simpler then CastInst::getCastOpcode.
486static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
487 Type *SrcTy = V->getType();
488 if (SrcTy->isStructTy()) {
489 assert(DestTy->isStructTy())((DestTy->isStructTy()) ? static_cast<void> (0) : __assert_fail
("DestTy->isStructTy()", "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 489, __PRETTY_FUNCTION__))
;
490 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements())((SrcTy->getStructNumElements() == DestTy->getStructNumElements
()) ? static_cast<void> (0) : __assert_fail ("SrcTy->getStructNumElements() == DestTy->getStructNumElements()"
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 490, __PRETTY_FUNCTION__))
;
491 Value *Result = UndefValue::get(DestTy);
492 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
493 Value *Element = createCast(
494 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
495 DestTy->getStructElementType(I));
496
497 Result =
498 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
499 }
500 return Result;
501 }
502 assert(!DestTy->isStructTy())((!DestTy->isStructTy()) ? static_cast<void> (0) : __assert_fail
("!DestTy->isStructTy()", "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 502, __PRETTY_FUNCTION__))
;
503 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
504 return Builder.CreateIntToPtr(V, DestTy);
505 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
506 return Builder.CreatePtrToInt(V, DestTy);
507 else
508 return Builder.CreateBitCast(V, DestTy);
509}
510
511// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
512// parameter debug info, from the entry block.
513void MergeFunctions::eraseInstsUnrelatedToPDI(
514 std::vector<Instruction *> &PDIUnrelatedWL) {
515 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Erasing instructions (in reverse order of appearance in "
"entry block) unrelated to parameter debug info from entry "
"block: {\n"; } } while (false)
516 dbgs() << " Erasing instructions (in reverse order of appearance in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Erasing instructions (in reverse order of appearance in "
"entry block) unrelated to parameter debug info from entry "
"block: {\n"; } } while (false)
517 "entry block) unrelated to parameter debug info from entry "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Erasing instructions (in reverse order of appearance in "
"entry block) unrelated to parameter debug info from entry "
"block: {\n"; } } while (false)
518 "block: {\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Erasing instructions (in reverse order of appearance in "
"entry block) unrelated to parameter debug info from entry "
"block: {\n"; } } while (false)
;
519 while (!PDIUnrelatedWL.empty()) {
520 Instruction *I = PDIUnrelatedWL.back();
521 LLVM_DEBUG(dbgs() << " Deleting Instruction: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Deleting Instruction: "; }
} while (false)
;
522 LLVM_DEBUG(I->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { I->print(dbgs()); } } while (false)
;
523 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
524 I->eraseFromParent();
525 PDIUnrelatedWL.pop_back();
526 }
527 LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " } // Done erasing instructions unrelated to parameter "
"debug info from entry block. \n"; } } while (false)
528 "debug info from entry block. \n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " } // Done erasing instructions unrelated to parameter "
"debug info from entry block. \n"; } } while (false)
;
529}
530
531// Reduce G to its entry block.
532void MergeFunctions::eraseTail(Function *G) {
533 std::vector<BasicBlock *> WorklistBB;
534 for (Function::iterator BBI = std::next(G->begin()), BBE = G->end();
535 BBI != BBE; ++BBI) {
536 BBI->dropAllReferences();
537 WorklistBB.push_back(&*BBI);
538 }
539 while (!WorklistBB.empty()) {
540 BasicBlock *BB = WorklistBB.back();
541 BB->eraseFromParent();
542 WorklistBB.pop_back();
543 }
544}
545
546// We are interested in the following instructions from the entry block as being
547// related to parameter debug info:
548// - @llvm.dbg.declare
549// - stores from the incoming parameters to locations on the stack-frame
550// - allocas that create these locations on the stack-frame
551// - @llvm.dbg.value
552// - the entry block's terminator
553// The rest are unrelated to debug info for the parameters; fill up
554// PDIUnrelatedWL with such instructions.
555void MergeFunctions::filterInstsUnrelatedToPDI(
556 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
557 std::set<Instruction *> PDIRelated;
558 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
559 BI != BIE; ++BI) {
560 if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
561 LLVM_DEBUG(dbgs() << " Deciding: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Deciding: "; } } while (false
)
;
562 LLVM_DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
563 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
564 DILocalVariable *DILocVar = DVI->getVariable();
565 if (DILocVar->isParameter()) {
566 LLVM_DEBUG(dbgs() << " Include (parameter): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Include (parameter): "; }
} while (false)
;
567 LLVM_DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
568 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
569 PDIRelated.insert(&*BI);
570 } else {
571 LLVM_DEBUG(dbgs() << " Delete (!parameter): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Delete (!parameter): "; }
} while (false)
;
572 LLVM_DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
573 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
574 }
575 } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
576 LLVM_DEBUG(dbgs() << " Deciding: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Deciding: "; } } while (false
)
;
577 LLVM_DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
578 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
579 DILocalVariable *DILocVar = DDI->getVariable();
580 if (DILocVar->isParameter()) {
581 LLVM_DEBUG(dbgs() << " Parameter: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Parameter: "; } } while (
false)
;
582 LLVM_DEBUG(DILocVar->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { DILocVar->print(dbgs()); } } while (false
)
;
583 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
584 if (AI) {
585 LLVM_DEBUG(dbgs() << " Processing alloca users: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Processing alloca users: "
; } } while (false)
;
586 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
587 for (User *U : AI->users()) {
588 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
589 if (Value *Arg = SI->getValueOperand()) {
590 if (dyn_cast<Argument>(Arg)) {
591 LLVM_DEBUG(dbgs() << " Include: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Include: "; } } while (false
)
;
592 LLVM_DEBUG(AI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { AI->print(dbgs()); } } while (false)
;
593 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
594 PDIRelated.insert(AI);
595 LLVM_DEBUG(dbgs() << " Include (parameter): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Include (parameter): "; }
} while (false)
;
596 LLVM_DEBUG(SI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { SI->print(dbgs()); } } while (false)
;
597 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
598 PDIRelated.insert(SI);
599 LLVM_DEBUG(dbgs() << " Include: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Include: "; } } while (false
)
;
600 LLVM_DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
601 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
602 PDIRelated.insert(&*BI);
603 } else {
604 LLVM_DEBUG(dbgs() << " Delete (!parameter): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Delete (!parameter): "; }
} while (false)
;
605 LLVM_DEBUG(SI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { SI->print(dbgs()); } } while (false)
;
606 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
607 }
608 }
609 } else {
610 LLVM_DEBUG(dbgs() << " Defer: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Defer: "; } } while (false
)
;
611 LLVM_DEBUG(U->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { U->print(dbgs()); } } while (false)
;
612 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
613 }
614 }
615 } else {
616 LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Delete (alloca NULL): "; }
} while (false)
;
617 LLVM_DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
618 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
619 }
620 } else {
621 LLVM_DEBUG(dbgs() << " Delete (!parameter): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Delete (!parameter): "; }
} while (false)
;
622 LLVM_DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
623 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
624 }
625 } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
626 LLVM_DEBUG(dbgs() << " Will Include Terminator: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Will Include Terminator: "
; } } while (false)
;
627 LLVM_DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
628 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
629 PDIRelated.insert(&*BI);
630 } else {
631 LLVM_DEBUG(dbgs() << " Defer: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Defer: "; } } while (false
)
;
632 LLVM_DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
633 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
634 }
635 }
636 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Report parameter debug info related/related instructions: {\n"
; } } while (false)
637 dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Report parameter debug info related/related instructions: {\n"
; } } while (false)
638 << " Report parameter debug info related/related instructions: {\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Report parameter debug info related/related instructions: {\n"
; } } while (false)
;
639 for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end();
640 BI != BE; ++BI) {
641
642 Instruction *I = &*BI;
643 if (PDIRelated.find(I) == PDIRelated.end()) {
644 LLVM_DEBUG(dbgs() << " !PDIRelated: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " !PDIRelated: "; } } while
(false)
;
645 LLVM_DEBUG(I->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { I->print(dbgs()); } } while (false)
;
646 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
647 PDIUnrelatedWL.push_back(I);
648 } else {
649 LLVM_DEBUG(dbgs() << " PDIRelated: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " PDIRelated: "; } } while
(false)
;
650 LLVM_DEBUG(I->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { I->print(dbgs()); } } while (false)
;
651 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
652 }
653 }
654 LLVM_DEBUG(dbgs() << " }\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " }\n"; } } while (false)
;
655}
656
657// Don't merge tiny functions using a thunk, since it can just end up
658// making the function larger.
659static bool isThunkProfitable(Function * F) {
660 if (F->size() == 1) {
661 if (F->front().size() <= 2) {
662 LLVM_DEBUG(dbgs() << "isThunkProfitable: " << F->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "isThunkProfitable: " <<
F->getName() << " is too small to bother creating a thunk for\n"
; } } while (false)
663 << " is too small to bother creating a thunk for\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "isThunkProfitable: " <<
F->getName() << " is too small to bother creating a thunk for\n"
; } } while (false)
;
664 return false;
665 }
666 }
667 return true;
668}
669
670// Replace G with a simple tail call to bitcast(F). Also (unless
671// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
672// delete G. Under MergeFunctionsPDI, we use G itself for creating
673// the thunk as we preserve the debug info (and associated instructions)
674// from G's entry block pertaining to G's incoming arguments which are
675// passed on as corresponding arguments in the call that G makes to F.
676// For better debugability, under MergeFunctionsPDI, we do not modify G's
677// call sites to point to F even when within the same translation unit.
678void MergeFunctions::writeThunk(Function *F, Function *G) {
679 BasicBlock *GEntryBlock = nullptr;
680 std::vector<Instruction *> PDIUnrelatedWL;
681 BasicBlock *BB = nullptr;
682 Function *NewG = nullptr;
24
'NewG' initialized to a null pointer value
683 if (MergeFunctionsPDI) {
25
Assuming the condition is true
26
Taking true branch
684 LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
"function as thunk; retain original: " << G->getName
() << "()\n"; } } while (false)
27
Assuming 'DebugFlag' is 0
28
Loop condition is false. Exiting loop
685 "function as thunk; retain original: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
"function as thunk; retain original: " << G->getName
() << "()\n"; } } while (false)
686 << G->getName() << "()\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
"function as thunk; retain original: " << G->getName
() << "()\n"; } } while (false)
;
687 GEntryBlock = &G->getEntryBlock();
688 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
"debug info for " << G->getName() << "() {\n"
; } } while (false)
29
Assuming 'DebugFlag' is 0
30
Loop condition is false. Exiting loop
689 dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
"debug info for " << G->getName() << "() {\n"
; } } while (false)
690 "debug info for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
"debug info for " << G->getName() << "() {\n"
; } } while (false)
691 << G->getName() << "() {\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
"debug info for " << G->getName() << "() {\n"
; } } while (false)
;
692 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
693 GEntryBlock->getTerminator()->eraseFromParent();
694 BB = GEntryBlock;
695 } else {
696 NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
697 G->getAddressSpace(), "", G->getParent());
698 BB = BasicBlock::Create(F->getContext(), "", NewG);
699 }
700
701 IRBuilder<> Builder(BB);
702 Function *H = MergeFunctionsPDI ? G : NewG;
31
Assuming the condition is false
32
'?' condition is false
33
'H' initialized to a null pointer value
703 SmallVector<Value *, 16> Args;
704 unsigned i = 0;
705 FunctionType *FFTy = F->getFunctionType();
706 for (Argument &AI : H->args()) {
34
Called C++ object pointer is null
707 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
708 ++i;
709 }
710
711 CallInst *CI = Builder.CreateCall(F, Args);
712 ReturnInst *RI = nullptr;
713 CI->setTailCall();
714 CI->setCallingConv(F->getCallingConv());
715 CI->setAttributes(F->getAttributes());
716 if (H->getReturnType()->isVoidTy()) {
717 RI = Builder.CreateRetVoid();
718 } else {
719 RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
720 }
721
722 if (MergeFunctionsPDI) {
723 DISubprogram *DIS = G->getSubprogram();
724 if (DIS) {
725 DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
726 DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
727 CI->setDebugLoc(CIDbgLoc);
728 RI->setDebugLoc(RIDbgLoc);
729 } else {
730 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
<< G->getName() << "()\n"; } } while (false)
731 dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
<< G->getName() << "()\n"; } } while (false)
732 << G->getName() << "()\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
<< G->getName() << "()\n"; } } while (false)
;
733 }
734 eraseTail(G);
735 eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
736 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "} // End of parameter related debug info filtering for: "
<< G->getName() << "()\n"; } } while (false)
737 dbgs() << "} // End of parameter related debug info filtering for: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "} // End of parameter related debug info filtering for: "
<< G->getName() << "()\n"; } } while (false)
738 << G->getName() << "()\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "} // End of parameter related debug info filtering for: "
<< G->getName() << "()\n"; } } while (false)
;
739 } else {
740 NewG->copyAttributesFrom(G);
741 NewG->takeName(G);
742 removeUsers(G);
743 G->replaceAllUsesWith(NewG);
744 G->eraseFromParent();
745 }
746
747 LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: " << H->
getName() << '\n'; } } while (false)
;
748 ++NumThunksWritten;
749}
750
751// Whether this function may be replaced by an alias
752static bool canCreateAliasFor(Function *F) {
753 if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
754 return false;
755
756 // We should only see linkages supported by aliases here
757 assert(F->hasLocalLinkage() || F->hasExternalLinkage()((F->hasLocalLinkage() || F->hasExternalLinkage() || F->
hasWeakLinkage() || F->hasLinkOnceLinkage()) ? static_cast
<void> (0) : __assert_fail ("F->hasLocalLinkage() || F->hasExternalLinkage() || F->hasWeakLinkage() || F->hasLinkOnceLinkage()"
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 758, __PRETTY_FUNCTION__))
758 || F->hasWeakLinkage() || F->hasLinkOnceLinkage())((F->hasLocalLinkage() || F->hasExternalLinkage() || F->
hasWeakLinkage() || F->hasLinkOnceLinkage()) ? static_cast
<void> (0) : __assert_fail ("F->hasLocalLinkage() || F->hasExternalLinkage() || F->hasWeakLinkage() || F->hasLinkOnceLinkage()"
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 758, __PRETTY_FUNCTION__))
;
759 return true;
760}
761
762// Replace G with an alias to F (deleting function G)
763void MergeFunctions::writeAlias(Function *F, Function *G) {
764 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
765 PointerType *PtrType = G->getType();
766 auto *GA = GlobalAlias::create(
767 PtrType->getElementType(), PtrType->getAddressSpace(),
768 G->getLinkage(), "", BitcastF, G->getParent());
769
770 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
771 GA->takeName(G);
772 GA->setVisibility(G->getVisibility());
773 GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
774
775 removeUsers(G);
776 G->replaceAllUsesWith(GA);
777 G->eraseFromParent();
778
779 LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeAlias: " << GA->
getName() << '\n'; } } while (false)
;
780 ++NumAliasesWritten;
781}
782
783// Replace G with an alias to F if possible, or a thunk to F if
784// profitable. Returns false if neither is the case.
785bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
786 if (canCreateAliasFor(G)) {
21
Taking false branch
787 writeAlias(F, G);
788 return true;
789 }
790 if (isThunkProfitable(F)) {
22
Taking true branch
791 writeThunk(F, G);
23
Calling 'MergeFunctions::writeThunk'
792 return true;
793 }
794 return false;
795}
796
797// Merge two equivalent functions. Upon completion, Function G is deleted.
798void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
799 if (F->isInterposable()) {
19
Taking false branch
800 assert(G->isInterposable())((G->isInterposable()) ? static_cast<void> (0) : __assert_fail
("G->isInterposable()", "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 800, __PRETTY_FUNCTION__))
;
801
802 // Both writeThunkOrAlias() calls below must succeed, either because we can
803 // create aliases for G and NewF, or because a thunk for F is profitable.
804 // F here has the same signature as NewF below, so that's what we check.
805 if (!isThunkProfitable(F) && (!canCreateAliasFor(F) || !canCreateAliasFor(G))) {
806 return;
807 }
808
809 // Make them both thunks to the same internal function.
810 Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
811 F->getAddressSpace(), "", F->getParent());
812 NewF->copyAttributesFrom(F);
813 NewF->takeName(F);
814 removeUsers(F);
815 F->replaceAllUsesWith(NewF);
816
817 unsigned MaxAlignment = std::max(G->getAlignment(), NewF->getAlignment());
818
819 writeThunkOrAlias(F, G);
820 writeThunkOrAlias(F, NewF);
821
822 F->setAlignment(MaxAlignment);
823 F->setLinkage(GlobalValue::PrivateLinkage);
824 ++NumDoubleWeak;
825 ++NumFunctionsMerged;
826 } else {
827 // For better debugability, under MergeFunctionsPDI, we do not modify G's
828 // call sites to point to F even when within the same translation unit.
829 if (!G->isInterposable() && !MergeFunctionsPDI) {
830 if (G->hasGlobalUnnamedAddr()) {
831 // G might have been a key in our GlobalNumberState, and it's illegal
832 // to replace a key in ValueMap<GlobalValue *> with a non-global.
833 GlobalNumbers.erase(G);
834 // If G's address is not significant, replace it entirely.
835 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
836 removeUsers(G);
837 G->replaceAllUsesWith(BitcastF);
838 } else {
839 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
840 // above).
841 replaceDirectCallers(G, F);
842 }
843 }
844
845 // If G was internal then we may have replaced all uses of G with F. If so,
846 // stop here and delete G. There's no need for a thunk. (See note on
847 // MergeFunctionsPDI above).
848 if (G->hasLocalLinkage() && G->use_empty() && !MergeFunctionsPDI) {
849 G->eraseFromParent();
850 ++NumFunctionsMerged;
851 return;
852 }
853
854 if (writeThunkOrAlias(F, G)) {
20
Calling 'MergeFunctions::writeThunkOrAlias'
855 ++NumFunctionsMerged;
856 }
857 }
858}
859
860/// Replace function F by function G.
861void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
862 Function *G) {
863 Function *F = FN.getFunc();
864 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&((FunctionComparator(F, G, &GlobalNumbers).compare() == 0
&& "The two functions must be equal") ? static_cast<
void> (0) : __assert_fail ("FunctionComparator(F, G, &GlobalNumbers).compare() == 0 && \"The two functions must be equal\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 865, __PRETTY_FUNCTION__))
865 "The two functions must be equal")((FunctionComparator(F, G, &GlobalNumbers).compare() == 0
&& "The two functions must be equal") ? static_cast<
void> (0) : __assert_fail ("FunctionComparator(F, G, &GlobalNumbers).compare() == 0 && \"The two functions must be equal\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 865, __PRETTY_FUNCTION__))
;
866
867 auto I = FNodesInTree.find(F);
868 assert(I != FNodesInTree.end() && "F should be in FNodesInTree")((I != FNodesInTree.end() && "F should be in FNodesInTree"
) ? static_cast<void> (0) : __assert_fail ("I != FNodesInTree.end() && \"F should be in FNodesInTree\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 868, __PRETTY_FUNCTION__))
;
869 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G")((FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G"
) ? static_cast<void> (0) : __assert_fail ("FNodesInTree.count(G) == 0 && \"FNodesInTree should not contain G\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 869, __PRETTY_FUNCTION__))
;
870
871 FnTreeType::iterator IterToFNInFnTree = I->second;
872 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.")((&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree."
) ? static_cast<void> (0) : __assert_fail ("&(*IterToFNInFnTree) == &FN && \"F should map to FN in FNodesInTree.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 872, __PRETTY_FUNCTION__))
;
873 // Remove F -> FN and insert G -> FN
874 FNodesInTree.erase(I);
875 FNodesInTree.insert({G, IterToFNInFnTree});
876 // Replace F with G in FN, which is stored inside the FnTree.
877 FN.replaceBy(G);
878}
879
880// Ordering for functions that are equal under FunctionComparator
881static bool isFuncOrderCorrect(const Function *F, const Function *G) {
882 if (F->isInterposable() != G->isInterposable()) {
883 // Strong before weak, because the weak function may call the strong
884 // one, but not the other way around.
885 return !F->isInterposable();
886 }
887 if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
888 // External before local, because we definitely have to keep the external
889 // function, but may be able to drop the local one.
890 return !F->hasLocalLinkage();
891 }
892 // Impose a total order (by name) on the replacement of functions. This is
893 // important when operating on more than one module independently to prevent
894 // cycles of thunks calling each other when the modules are linked together.
895 return F->getName() <= G->getName();
896}
897
898// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
899// that was already inserted.
900bool MergeFunctions::insert(Function *NewFunction) {
901 std::pair<FnTreeType::iterator, bool> Result =
902 FnTree.insert(FunctionNode(NewFunction));
903
904 if (Result.second) {
13
Assuming the condition is false
14
Taking false branch
905 assert(FNodesInTree.count(NewFunction) == 0)((FNodesInTree.count(NewFunction) == 0) ? static_cast<void
> (0) : __assert_fail ("FNodesInTree.count(NewFunction) == 0"
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 905, __PRETTY_FUNCTION__))
;
906 FNodesInTree.insert({NewFunction, Result.first});
907 LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "Inserting as unique: " <<
NewFunction->getName() << '\n'; } } while (false)
908 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "Inserting as unique: " <<
NewFunction->getName() << '\n'; } } while (false)
;
909 return false;
910 }
911
912 const FunctionNode &OldF = *Result.first;
913
914 if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
15
Taking false branch
915 // Swap the two functions.
916 Function *F = OldF.getFunc();
917 replaceFunctionInTree(*Result.first, NewFunction);
918 NewFunction = F;
919 assert(OldF.getFunc() != F && "Must have swapped the functions.")((OldF.getFunc() != F && "Must have swapped the functions."
) ? static_cast<void> (0) : __assert_fail ("OldF.getFunc() != F && \"Must have swapped the functions.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Transforms/IPO/MergeFunctions.cpp"
, 919, __PRETTY_FUNCTION__))
;
920 }
921
922 LLVM_DEBUG(dbgs() << " " << OldF.getFunc()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " " << OldF.getFunc()
->getName() << " == " << NewFunction->getName
() << '\n'; } } while (false)
16
Assuming 'DebugFlag' is 0
17
Loop condition is false. Exiting loop
923 << " == " << NewFunction->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " " << OldF.getFunc()
->getName() << " == " << NewFunction->getName
() << '\n'; } } while (false)
;
924
925 Function *DeleteF = NewFunction;
926 mergeTwoFunctions(OldF.getFunc(), DeleteF);
18
Calling 'MergeFunctions::mergeTwoFunctions'
927 return true;
928}
929
930// Remove a function from FnTree. If it was already in FnTree, add
931// it to Deferred so that we'll look at it in the next round.
932void MergeFunctions::remove(Function *F) {
933 auto I = FNodesInTree.find(F);
934 if (I != FNodesInTree.end()) {
935 LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "Deferred " << F->getName
() << ".\n"; } } while (false)
;
936 FnTree.erase(I->second);
937 // I->second has been invalidated, remove it from the FNodesInTree map to
938 // preserve the invariant.
939 FNodesInTree.erase(I);
940 Deferred.emplace_back(F);
941 }
942}
943
944// For each instruction used by the value, remove() the function that contains
945// the instruction. This should happen right before a call to RAUW.
946void MergeFunctions::removeUsers(Value *V) {
947 std::vector<Value *> Worklist;
948 Worklist.push_back(V);
949 SmallPtrSet<Value*, 8> Visited;
950 Visited.insert(V);
951 while (!Worklist.empty()) {
952 Value *V = Worklist.back();
953 Worklist.pop_back();
954
955 for (User *U : V->users()) {
956 if (Instruction *I = dyn_cast<Instruction>(U)) {
957 remove(I->getParent()->getParent());
958 } else if (isa<GlobalValue>(U)) {
959 // do nothing
960 } else if (Constant *C = dyn_cast<Constant>(U)) {
961 for (User *UU : C->users()) {
962 if (!Visited.insert(UU).second)
963 Worklist.push_back(UU);
964 }
965 }
966 }
967 }
968}