Bug Summary

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

Annotated Source Code

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/Hashing.h"
93#include "llvm/ADT/STLExtras.h"
94#include "llvm/ADT/SmallSet.h"
95#include "llvm/ADT/Statistic.h"
96#include "llvm/IR/CallSite.h"
97#include "llvm/IR/Constants.h"
98#include "llvm/IR/DataLayout.h"
99#include "llvm/IR/DebugInfo.h"
100#include "llvm/IR/IRBuilder.h"
101#include "llvm/IR/Instructions.h"
102#include "llvm/IR/IntrinsicInst.h"
103#include "llvm/IR/LLVMContext.h"
104#include "llvm/IR/Module.h"
105#include "llvm/IR/ValueHandle.h"
106#include "llvm/IR/ValueMap.h"
107#include "llvm/Pass.h"
108#include "llvm/Support/CommandLine.h"
109#include "llvm/Support/Debug.h"
110#include "llvm/Support/ErrorHandling.h"
111#include "llvm/Support/raw_ostream.h"
112#include "llvm/Transforms/IPO.h"
113#include "llvm/Transforms/Utils/FunctionComparator.h"
114#include <vector>
115
116using namespace llvm;
117
118#define DEBUG_TYPE"mergefunc" "mergefunc"
119
120STATISTIC(NumFunctionsMerged, "Number of functions merged")static llvm::Statistic NumFunctionsMerged = {"mergefunc", "NumFunctionsMerged"
, "Number of functions merged", {0}, false}
;
121STATISTIC(NumThunksWritten, "Number of thunks generated")static llvm::Statistic NumThunksWritten = {"mergefunc", "NumThunksWritten"
, "Number of thunks generated", {0}, false}
;
122STATISTIC(NumAliasesWritten, "Number of aliases generated")static llvm::Statistic NumAliasesWritten = {"mergefunc", "NumAliasesWritten"
, "Number of aliases generated", {0}, false}
;
123STATISTIC(NumDoubleWeak, "Number of new functions created")static llvm::Statistic NumDoubleWeak = {"mergefunc", "NumDoubleWeak"
, "Number of new functions created", {0}, false}
;
124
125static cl::opt<unsigned> NumFunctionsForSanityCheck(
126 "mergefunc-sanity",
127 cl::desc("How many functions in module could be used for "
128 "MergeFunctions pass sanity check. "
129 "'0' disables this check. Works only with '-debug' key."),
130 cl::init(0), cl::Hidden);
131
132// Under option -mergefunc-preserve-debug-info we:
133// - Do not create a new function for a thunk.
134// - Retain the debug info for a thunk's parameters (and associated
135// instructions for the debug info) from the entry block.
136// Note: -debug will display the algorithm at work.
137// - Create debug-info for the call (to the shared implementation) made by
138// a thunk and its return value.
139// - Erase the rest of the function, retaining the (minimally sized) entry
140// block to create a thunk.
141// - Preserve a thunk's call site to point to the thunk even when both occur
142// within the same translation unit, to aid debugability. Note that this
143// behaviour differs from the underlying -mergefunc implementation which
144// modifies the thunk's call site to point to the shared implementation
145// when both occur within the same translation unit.
146static cl::opt<bool>
147 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
148 cl::init(false),
149 cl::desc("Preserve debug info in thunk when mergefunc "
150 "transformations are made."));
151
152namespace {
153
154class FunctionNode {
155 mutable AssertingVH<Function> F;
156 FunctionComparator::FunctionHash Hash;
157public:
158 // Note the hash is recalculated potentially multiple times, but it is cheap.
159 FunctionNode(Function *F)
160 : F(F), Hash(FunctionComparator::functionHash(*F)) {}
161 Function *getFunc() const { return F; }
162 FunctionComparator::FunctionHash getHash() const { return Hash; }
163
164 /// Replace the reference to the function F by the function G, assuming their
165 /// implementations are equal.
166 void replaceBy(Function *G) const {
167 F = G;
168 }
169
170 void release() { F = nullptr; }
171};
172
173/// MergeFunctions finds functions which will generate identical machine code,
174/// by considering all pointer types to be equivalent. Once identified,
175/// MergeFunctions will fold them by replacing a call to one to a call to a
176/// bitcast of the other.
177///
178class MergeFunctions : public ModulePass {
179public:
180 static char ID;
181 MergeFunctions()
182 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)), FNodesInTree(),
183 HasGlobalAliases(false) {
184 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry());
185 }
186
187 bool runOnModule(Module &M) override;
188
189private:
190 // The function comparison operator is provided here so that FunctionNodes do
191 // not need to become larger with another pointer.
192 class FunctionNodeCmp {
193 GlobalNumberState* GlobalNumbers;
194 public:
195 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
196 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
197 // Order first by hashes, then full function comparison.
198 if (LHS.getHash() != RHS.getHash())
199 return LHS.getHash() < RHS.getHash();
200 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
201 return FCmp.compare() == -1;
202 }
203 };
204 typedef std::set<FunctionNode, FunctionNodeCmp> FnTreeType;
205
206 GlobalNumberState GlobalNumbers;
207
208 /// A work queue of functions that may have been modified and should be
209 /// analyzed again.
210 std::vector<WeakVH> Deferred;
211
212 /// Checks the rules of order relation introduced among functions set.
213 /// Returns true, if sanity check has been passed, and false if failed.
214 bool doSanityCheck(std::vector<WeakVH> &Worklist);
215
216 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
217 /// equal to one that's already present.
218 bool insert(Function *NewFunction);
219
220 /// Remove a Function from the FnTree and queue it up for a second sweep of
221 /// analysis.
222 void remove(Function *F);
223
224 /// Find the functions that use this Value and remove them from FnTree and
225 /// queue the functions.
226 void removeUsers(Value *V);
227
228 /// Replace all direct calls of Old with calls of New. Will bitcast New if
229 /// necessary to make types match.
230 void replaceDirectCallers(Function *Old, Function *New);
231
232 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
233 /// be converted into a thunk. In either case, it should never be visited
234 /// again.
235 void mergeTwoFunctions(Function *F, Function *G);
236
237 /// Replace G with a thunk or an alias to F. Deletes G.
238 void writeThunkOrAlias(Function *F, Function *G);
239
240 /// Fill PDIUnrelatedWL with instructions from the entry block that are
241 /// unrelated to parameter related debug info.
242 void filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
243 std::vector<Instruction *> &PDIUnrelatedWL);
244
245 /// Erase the rest of the CFG (i.e. barring the entry block).
246 void eraseTail(Function *G);
247
248 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
249 /// parameter debug info, from the entry block.
250 void eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL);
251
252 /// Replace G with a simple tail call to bitcast(F). Also (unless
253 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
254 /// delete G.
255 void writeThunk(Function *F, Function *G);
256
257 /// Replace G with an alias to F. Deletes G.
258 void writeAlias(Function *F, Function *G);
259
260 /// Replace function F with function G in the function tree.
261 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
262
263 /// The set of all distinct functions. Use the insert() and remove() methods
264 /// to modify it. The map allows efficient lookup and deferring of Functions.
265 FnTreeType FnTree;
266 // Map functions to the iterators of the FunctionNode which contains them
267 // in the FnTree. This must be updated carefully whenever the FnTree is
268 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
269 // dangling iterators into FnTree. The invariant that preserves this is that
270 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
271 ValueMap<Function*, FnTreeType::iterator> FNodesInTree;
272
273 /// Whether or not the target supports global aliases.
274 bool HasGlobalAliases;
275};
276
277} // end anonymous namespace
278
279char MergeFunctions::ID = 0;
280INITIALIZE_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)); }
281
282ModulePass *llvm::createMergeFunctionsPass() {
283 return new MergeFunctions();
284}
285
286bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
287 if (const unsigned Max = NumFunctionsForSanityCheck) {
288 unsigned TripleNumber = 0;
289 bool Valid = true;
290
291 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n";
292
293 unsigned i = 0;
294 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end();
295 I != E && i < Max; ++I, ++i) {
296 unsigned j = i;
297 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) {
298 Function *F1 = cast<Function>(*I);
299 Function *F2 = cast<Function>(*J);
300 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
301 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
302
303 // If F1 <= F2, then F2 >= F1, otherwise report failure.
304 if (Res1 != -Res2) {
305 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber
306 << "\n";
307 dbgs() << *F1 << '\n' << *F2 << '\n';
308 Valid = false;
309 }
310
311 if (Res1 == 0)
312 continue;
313
314 unsigned k = j;
315 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max;
316 ++k, ++K, ++TripleNumber) {
317 if (K == J)
318 continue;
319
320 Function *F3 = cast<Function>(*K);
321 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
322 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
323
324 bool Transitive = true;
325
326 if (Res1 != 0 && Res1 == Res4) {
327 // F1 > F2, F2 > F3 => F1 > F3
328 Transitive = Res3 == Res1;
329 } else if (Res3 != 0 && Res3 == -Res4) {
330 // F1 > F3, F3 > F2 => F1 > F2
331 Transitive = Res3 == Res1;
332 } else if (Res4 != 0 && -Res3 == Res4) {
333 // F2 > F3, F3 > F1 => F2 > F1
334 Transitive = Res4 == -Res1;
335 }
336
337 if (!Transitive) {
338 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: "
339 << TripleNumber << "\n";
340 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
341 << Res4 << "\n";
342 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
343 Valid = false;
344 }
345 }
346 }
347 }
348
349 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n";
350 return Valid;
351 }
352 return true;
353}
354
355bool MergeFunctions::runOnModule(Module &M) {
356 if (skipModule(M))
357 return false;
358
359 bool Changed = false;
360
361 // All functions in the module, ordered by hash. Functions with a unique
362 // hash value are easily eliminated.
363 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
364 HashedFuncs;
365 for (Function &Func : M) {
366 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) {
367 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
368 }
369 }
370
371 std::stable_sort(
372 HashedFuncs.begin(), HashedFuncs.end(),
373 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
374 const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
375 return a.first < b.first;
376 });
377
378 auto S = HashedFuncs.begin();
379 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
380 // If the hash value matches the previous value or the next one, we must
381 // consider merging it. Otherwise it is dropped and never considered again.
382 if ((I != S && std::prev(I)->first == I->first) ||
383 (std::next(I) != IE && std::next(I)->first == I->first) ) {
384 Deferred.push_back(WeakVH(I->second));
385 }
386 }
387
388 do {
389 std::vector<WeakVH> Worklist;
390 Deferred.swap(Worklist);
391
392 DEBUG(doSanityCheck(Worklist))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { doSanityCheck(Worklist); } } while (false)
;
393
394 DEBUG(dbgs() << "size of module: " << M.size() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "size of module: " << M
.size() << '\n'; } } while (false)
;
395 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "size of worklist: " <<
Worklist.size() << '\n'; } } while (false)
;
396
397 // Insert functions and merge them.
398 for (WeakVH &I : Worklist) {
399 if (!I)
400 continue;
401 Function *F = cast<Function>(I);
402 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
403 Changed |= insert(F);
404 }
405 }
406 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "size of FnTree: " << FnTree
.size() << '\n'; } } while (false)
;
407 } while (!Deferred.empty());
408
409 FnTree.clear();
410 GlobalNumbers.clear();
411
412 return Changed;
413}
414
415// Replace direct callers of Old with New.
416void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
417 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
418 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
419 Use *U = &*UI;
420 ++UI;
421 CallSite CS(U->getUser());
422 if (CS && CS.isCallee(U)) {
423 // Transfer the called function's attributes to the call site. Due to the
424 // bitcast we will 'lose' ABI changing attributes because the 'called
425 // function' is no longer a Function* but the bitcast. Code that looks up
426 // the attributes from the called function will fail.
427
428 // FIXME: This is not actually true, at least not anymore. The callsite
429 // will always have the same ABI affecting attributes as the callee,
430 // because otherwise the original input has UB. Note that Old and New
431 // always have matching ABI, so no attributes need to be changed.
432 // Transferring other attributes may help other optimizations, but that
433 // should be done uniformly and not in this ad-hoc way.
434 auto &Context = New->getContext();
435 auto NewFuncAttrs = New->getAttributes();
436 auto CallSiteAttrs = CS.getAttributes();
437
438 CallSiteAttrs = CallSiteAttrs.addAttributes(
439 Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes());
440
441 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) {
442 AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx);
443 if (Attrs.getNumSlots())
444 CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs);
445 }
446
447 CS.setAttributes(CallSiteAttrs);
448
449 remove(CS.getInstruction()->getParent()->getParent());
450 U->set(BitcastNew);
451 }
452 }
453}
454
455// Replace G with an alias to F if possible, or else a thunk to F. Deletes G.
456void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
457 if (HasGlobalAliases && G->hasGlobalUnnamedAddr()) {
458 if (G->hasExternalLinkage() || G->hasLocalLinkage() ||
459 G->hasWeakLinkage()) {
460 writeAlias(F, G);
461 return;
462 }
463 }
464
465 writeThunk(F, G);
466}
467
468// Helper for writeThunk,
469// Selects proper bitcast operation,
470// but a bit simpler then CastInst::getCastOpcode.
471static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
472 Type *SrcTy = V->getType();
473 if (SrcTy->isStructTy()) {
474 assert(DestTy->isStructTy())((DestTy->isStructTy()) ? static_cast<void> (0) : __assert_fail
("DestTy->isStructTy()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 474, __PRETTY_FUNCTION__))
;
475 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements())((SrcTy->getStructNumElements() == DestTy->getStructNumElements
()) ? static_cast<void> (0) : __assert_fail ("SrcTy->getStructNumElements() == DestTy->getStructNumElements()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 475, __PRETTY_FUNCTION__))
;
476 Value *Result = UndefValue::get(DestTy);
477 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
478 Value *Element = createCast(
479 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
480 DestTy->getStructElementType(I));
481
482 Result =
483 Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
484 }
485 return Result;
486 }
487 assert(!DestTy->isStructTy())((!DestTy->isStructTy()) ? static_cast<void> (0) : __assert_fail
("!DestTy->isStructTy()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 487, __PRETTY_FUNCTION__))
;
488 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
489 return Builder.CreateIntToPtr(V, DestTy);
490 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
491 return Builder.CreatePtrToInt(V, DestTy);
492 else
493 return Builder.CreateBitCast(V, DestTy);
494}
495
496// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
497// parameter debug info, from the entry block.
498void MergeFunctions::eraseInstsUnrelatedToPDI(
499 std::vector<Instruction *> &PDIUnrelatedWL) {
500
501 DEBUG(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)
502 "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)
503 "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)
;
504 while (!PDIUnrelatedWL.empty()) {
505 Instruction *I = PDIUnrelatedWL.back();
506 DEBUG(dbgs() << " Deleting Instruction: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Deleting Instruction: "; }
} while (false)
;
507 DEBUG(I->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { I->print(dbgs()); } } while (false)
;
508 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
509 I->eraseFromParent();
510 PDIUnrelatedWL.pop_back();
511 }
512 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)
513 "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)
;
514}
515
516// Reduce G to its entry block.
517void MergeFunctions::eraseTail(Function *G) {
518
519 std::vector<BasicBlock *> WorklistBB;
520 for (Function::iterator BBI = std::next(G->begin()), BBE = G->end();
521 BBI != BBE; ++BBI) {
522 BBI->dropAllReferences();
523 WorklistBB.push_back(&*BBI);
524 }
525 while (!WorklistBB.empty()) {
526 BasicBlock *BB = WorklistBB.back();
527 BB->eraseFromParent();
528 WorklistBB.pop_back();
529 }
530}
531
532// We are interested in the following instructions from the entry block as being
533// related to parameter debug info:
534// - @llvm.dbg.declare
535// - stores from the incoming parameters to locations on the stack-frame
536// - allocas that create these locations on the stack-frame
537// - @llvm.dbg.value
538// - the entry block's terminator
539// The rest are unrelated to debug info for the parameters; fill up
540// PDIUnrelatedWL with such instructions.
541void MergeFunctions::filterInstsUnrelatedToPDI(
542 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
543
544 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)) {
548 DEBUG(dbgs() << " Deciding: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Deciding: "; } } while (false
)
;
549 DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
550 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
551 DILocalVariable *DILocVar = DVI->getVariable();
552 if (DILocVar->isParameter()) {
553 DEBUG(dbgs() << " Include (parameter): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Include (parameter): "; }
} while (false)
;
554 DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
555 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
556 PDIRelated.insert(&*BI);
557 } else {
558 DEBUG(dbgs() << " Delete (!parameter): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Delete (!parameter): "; }
} while (false)
;
559 DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
560 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
561 }
562 } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
563 DEBUG(dbgs() << " Deciding: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Deciding: "; } } while (false
)
;
564 DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
565 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
566 DILocalVariable *DILocVar = DDI->getVariable();
567 if (DILocVar->isParameter()) {
568 DEBUG(dbgs() << " Parameter: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Parameter: "; } } while (
false)
;
569 DEBUG(DILocVar->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { DILocVar->print(dbgs()); } } while (false
)
;
570 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
571 if (AI) {
572 DEBUG(dbgs() << " Processing alloca users: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Processing alloca users: "
; } } while (false)
;
573 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
574 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)) {
578 DEBUG(dbgs() << " Include: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Include: "; } } while (false
)
;
579 DEBUG(AI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { AI->print(dbgs()); } } while (false)
;
580 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
581 PDIRelated.insert(AI);
582 DEBUG(dbgs() << " Include (parameter): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Include (parameter): "; }
} while (false)
;
583 DEBUG(SI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { SI->print(dbgs()); } } while (false)
;
584 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
585 PDIRelated.insert(SI);
586 DEBUG(dbgs() << " Include: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Include: "; } } while (false
)
;
587 DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
588 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
589 PDIRelated.insert(&*BI);
590 } else {
591 DEBUG(dbgs() << " Delete (!parameter): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Delete (!parameter): "; }
} while (false)
;
592 DEBUG(SI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { SI->print(dbgs()); } } while (false)
;
593 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
594 }
595 }
596 } else {
597 DEBUG(dbgs() << " Defer: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Defer: "; } } while (false
)
;
598 DEBUG(U->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { U->print(dbgs()); } } while (false)
;
599 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
600 }
601 }
602 } else {
603 DEBUG(dbgs() << " Delete (alloca NULL): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Delete (alloca NULL): "; }
} while (false)
;
604 DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
605 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
606 }
607 } else {
608 DEBUG(dbgs() << " Delete (!parameter): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Delete (!parameter): "; }
} while (false)
;
609 DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
610 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
611 }
612 } else if (dyn_cast<TerminatorInst>(BI) == GEntryBlock->getTerminator()) {
613 DEBUG(dbgs() << " Will Include Terminator: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Will Include Terminator: "
; } } while (false)
;
614 DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
615 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
616 PDIRelated.insert(&*BI);
617 } else {
618 DEBUG(dbgs() << " Defer: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Defer: "; } } while (false
)
;
619 DEBUG(BI->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { BI->print(dbgs()); } } while (false)
;
620 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
621 }
622 }
623 DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " Report parameter debug info related/related instructions: {\n"
; } } while (false)
624 << " 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)
;
625 for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end();
626 BI != BE; ++BI) {
627
628 Instruction *I = &*BI;
629 if (PDIRelated.find(I) == PDIRelated.end()) {
630 DEBUG(dbgs() << " !PDIRelated: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " !PDIRelated: "; } } while
(false)
;
631 DEBUG(I->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { I->print(dbgs()); } } while (false)
;
632 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
633 PDIUnrelatedWL.push_back(I);
634 } else {
635 DEBUG(dbgs() << " PDIRelated: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " PDIRelated: "; } } while
(false)
;
636 DEBUG(I->print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { I->print(dbgs()); } } while (false)
;
637 DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "\n"; } } while (false)
;
638 }
639 }
640 DEBUG(dbgs() << " }\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " }\n"; } } while (false)
;
641}
642
643// Replace G with a simple tail call to bitcast(F). Also (unless
644// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
645// delete G. Under MergeFunctionsPDI, we use G itself for creating
646// the thunk as we preserve the debug info (and associated instructions)
647// from G's entry block pertaining to G's incoming arguments which are
648// passed on as corresponding arguments in the call that G makes to F.
649// For better debugability, under MergeFunctionsPDI, we do not modify G's
650// call sites to point to F even when within the same translation unit.
651void MergeFunctions::writeThunk(Function *F, Function *G) {
652 if (!G->isInterposable() && !MergeFunctionsPDI) {
1
Assuming the condition is false
2
Taking false branch
653 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
654 // above).
655 replaceDirectCallers(G, F);
656 }
657
658 // If G was internal then we may have replaced all uses of G with F. If so,
659 // stop here and delete G. There's no need for a thunk. (See note on
660 // MergeFunctionsPDI above).
661 if (G->hasLocalLinkage() && G->use_empty() && !MergeFunctionsPDI) {
662 G->eraseFromParent();
663 return;
664 }
665
666 BasicBlock *GEntryBlock = nullptr;
667 std::vector<Instruction *> PDIUnrelatedWL;
668 BasicBlock *BB = nullptr;
669 Function *NewG = nullptr;
3
'NewG' initialized to a null pointer value
670 if (MergeFunctionsPDI) {
4
Taking true branch
671 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)
672 "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)
673 << 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)
;
674 GEntryBlock = &G->getEntryBlock();
675 DEBUG(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)
676 "debug info for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
"debug info for " << G->getName() << "() {\n"
; } } while (false)
677 << G->getName() << "() {\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
"debug info for " << G->getName() << "() {\n"
; } } while (false)
;
678 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
679 GEntryBlock->getTerminator()->eraseFromParent();
680 BB = GEntryBlock;
681 } else {
682 NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "",
683 G->getParent());
684 BB = BasicBlock::Create(F->getContext(), "", NewG);
685 }
686
687 IRBuilder<> Builder(BB);
688 Function *H = MergeFunctionsPDI ? G : NewG;
5
Assuming the condition is false
6
'?' condition is false
7
'H' initialized to a null pointer value
689 SmallVector<Value *, 16> Args;
690 unsigned i = 0;
691 FunctionType *FFTy = F->getFunctionType();
692 for (Argument & AI : H->args()) {
8
Called C++ object pointer is null
693 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
694 ++i;
695 }
696
697 CallInst *CI = Builder.CreateCall(F, Args);
698 ReturnInst *RI = nullptr;
699 CI->setTailCall();
700 CI->setCallingConv(F->getCallingConv());
701 CI->setAttributes(F->getAttributes());
702 if (H->getReturnType()->isVoidTy()) {
703 RI = Builder.CreateRetVoid();
704 } else {
705 RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
706 }
707
708 if (MergeFunctionsPDI) {
709 DISubprogram *DIS = G->getSubprogram();
710 if (DIS) {
711 DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
712 DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
713 CI->setDebugLoc(CIDbgLoc);
714 RI->setDebugLoc(RIDbgLoc);
715 } else {
716 DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
<< G->getName() << "()\n"; } } while (false)
717 << G->getName() << "()\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
<< G->getName() << "()\n"; } } while (false)
;
718 }
719 eraseTail(G);
720 eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
721 DEBUG(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)
722 << G->getName() << "()\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "} // End of parameter related debug info filtering for: "
<< G->getName() << "()\n"; } } while (false)
;
723 } else {
724 NewG->copyAttributesFrom(G);
725 NewG->takeName(G);
726 removeUsers(G);
727 G->replaceAllUsesWith(NewG);
728 G->eraseFromParent();
729 }
730
731 DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeThunk: " << H->
getName() << '\n'; } } while (false)
;
732 ++NumThunksWritten;
733}
734
735// Replace G with an alias to F and delete G.
736void MergeFunctions::writeAlias(Function *F, Function *G) {
737 auto *GA = GlobalAlias::create(G->getLinkage(), "", F);
738 F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
739 GA->takeName(G);
740 GA->setVisibility(G->getVisibility());
741 removeUsers(G);
742 G->replaceAllUsesWith(GA);
743 G->eraseFromParent();
744
745 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "writeAlias: " << GA->
getName() << '\n'; } } while (false)
;
746 ++NumAliasesWritten;
747}
748
749// Merge two equivalent functions. Upon completion, Function G is deleted.
750void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
751 if (F->isInterposable()) {
752 assert(G->isInterposable())((G->isInterposable()) ? static_cast<void> (0) : __assert_fail
("G->isInterposable()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 752, __PRETTY_FUNCTION__))
;
753
754 // Make them both thunks to the same internal function.
755 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "",
756 F->getParent());
757 H->copyAttributesFrom(F);
758 H->takeName(F);
759 removeUsers(F);
760 F->replaceAllUsesWith(H);
761
762 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment());
763
764 if (HasGlobalAliases) {
765 writeAlias(F, G);
766 writeAlias(F, H);
767 } else {
768 writeThunk(F, G);
769 writeThunk(F, H);
770 }
771
772 F->setAlignment(MaxAlignment);
773 F->setLinkage(GlobalValue::PrivateLinkage);
774 ++NumDoubleWeak;
775 } else {
776 writeThunkOrAlias(F, G);
777 }
778
779 ++NumFunctionsMerged;
780}
781
782/// Replace function F by function G.
783void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
784 Function *G) {
785 Function *F = FN.getFunc();
786 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 787, __PRETTY_FUNCTION__))
787 "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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 787, __PRETTY_FUNCTION__))
;
788
789 auto I = FNodesInTree.find(F);
790 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 790, __PRETTY_FUNCTION__))
;
791 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 791, __PRETTY_FUNCTION__))
;
792
793 FnTreeType::iterator IterToFNInFnTree = I->second;
794 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 794, __PRETTY_FUNCTION__))
;
795 // Remove F -> FN and insert G -> FN
796 FNodesInTree.erase(I);
797 FNodesInTree.insert({G, IterToFNInFnTree});
798 // Replace F with G in FN, which is stored inside the FnTree.
799 FN.replaceBy(G);
800}
801
802// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
803// that was already inserted.
804bool MergeFunctions::insert(Function *NewFunction) {
805 std::pair<FnTreeType::iterator, bool> Result =
806 FnTree.insert(FunctionNode(NewFunction));
807
808 if (Result.second) {
809 assert(FNodesInTree.count(NewFunction) == 0)((FNodesInTree.count(NewFunction) == 0) ? static_cast<void
> (0) : __assert_fail ("FNodesInTree.count(NewFunction) == 0"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 809, __PRETTY_FUNCTION__))
;
810 FNodesInTree.insert({NewFunction, Result.first});
811 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "Inserting as unique: " <<
NewFunction->getName() << '\n'; } } while (false)
;
812 return false;
813 }
814
815 const FunctionNode &OldF = *Result.first;
816
817 // Don't merge tiny functions, since it can just end up making the function
818 // larger.
819 // FIXME: Should still merge them if they are unnamed_addr and produce an
820 // alias.
821 if (NewFunction->size() == 1) {
822 if (NewFunction->front().size() <= 2) {
823 DEBUG(dbgs() << NewFunction->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << NewFunction->getName() <<
" is to small to bother merging\n"; } } while (false)
824 << " is to small to bother merging\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << NewFunction->getName() <<
" is to small to bother merging\n"; } } while (false)
;
825 return false;
826 }
827 }
828
829 // Impose a total order (by name) on the replacement of functions. This is
830 // important when operating on more than one module independently to prevent
831 // cycles of thunks calling each other when the modules are linked together.
832 //
833 // First of all, we process strong functions before weak functions.
834 if ((OldF.getFunc()->isInterposable() && !NewFunction->isInterposable()) ||
835 (OldF.getFunc()->isInterposable() == NewFunction->isInterposable() &&
836 OldF.getFunc()->getName() > NewFunction->getName())) {
837 // Swap the two functions.
838 Function *F = OldF.getFunc();
839 replaceFunctionInTree(*Result.first, NewFunction);
840 NewFunction = F;
841 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/lib/Transforms/IPO/MergeFunctions.cpp"
, 841, __PRETTY_FUNCTION__))
;
842 }
843
844 DEBUG(dbgs() << " " << OldF.getFunc()->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " " << OldF.getFunc()
->getName() << " == " << NewFunction->getName
() << '\n'; } } while (false)
845 << " == " << NewFunction->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << " " << OldF.getFunc()
->getName() << " == " << NewFunction->getName
() << '\n'; } } while (false)
;
846
847 Function *DeleteF = NewFunction;
848 mergeTwoFunctions(OldF.getFunc(), DeleteF);
849 return true;
850}
851
852// Remove a function from FnTree. If it was already in FnTree, add
853// it to Deferred so that we'll look at it in the next round.
854void MergeFunctions::remove(Function *F) {
855 auto I = FNodesInTree.find(F);
856 if (I != FNodesInTree.end()) {
857 DEBUG(dbgs() << "Deferred " << F->getName()<< ".\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mergefunc")) { dbgs() << "Deferred " << F->getName
()<< ".\n"; } } while (false)
;
858 FnTree.erase(I->second);
859 // I->second has been invalidated, remove it from the FNodesInTree map to
860 // preserve the invariant.
861 FNodesInTree.erase(I);
862 Deferred.emplace_back(F);
863 }
864}
865
866// For each instruction used by the value, remove() the function that contains
867// the instruction. This should happen right before a call to RAUW.
868void MergeFunctions::removeUsers(Value *V) {
869 std::vector<Value *> Worklist;
870 Worklist.push_back(V);
871 SmallSet<Value*, 8> Visited;
872 Visited.insert(V);
873 while (!Worklist.empty()) {
874 Value *V = Worklist.back();
875 Worklist.pop_back();
876
877 for (User *U : V->users()) {
878 if (Instruction *I = dyn_cast<Instruction>(U)) {
879 remove(I->getParent()->getParent());
880 } else if (isa<GlobalValue>(U)) {
881 // do nothing
882 } else if (Constant *C = dyn_cast<Constant>(U)) {
883 for (User *UU : C->users()) {
884 if (!Visited.insert(UU).second)
885 Worklist.push_back(UU);
886 }
887 }
888 }
889 }
890}