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 
133 using namespace llvm;
134 
135 #define DEBUG_TYPE "mergefunc"
136 
137 STATISTIC(NumFunctionsMerged, "Number of functions merged");
138 STATISTIC(NumThunksWritten, "Number of thunks generated");
139 STATISTIC(NumAliasesWritten, "Number of aliases generated");
140 STATISTIC(NumDoubleWeak, "Number of new functions created");
141 
142 static 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.
163 static 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 
169 static cl::opt<bool>
170     MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
171                           cl::init(false),
172                           cl::desc("Allow mergefunc to create aliases"));
173 
174 namespace {
175 
176 class FunctionNode {
177   mutable AssertingVH<Function> F;
178   FunctionComparator::FunctionHash Hash;
179 
180 public:
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.
201 class MergeFunctions : public ModulePass {
202 public:
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 
212 private:
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 possible.
285   // 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 
305 char MergeFunctions::ID = 0;
306 
307 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false)
308 
309 ModulePass *llvm::createMergeFunctionsPass() {
310   return new MergeFunctions();
311 }
312 
313 #ifndef NDEBUG
314 bool 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 
386 /// Check whether \p F is eligible for function merging.
387 static bool isEligibleForMerging(Function &F) {
388   return !F.isDeclaration() && !F.hasAvailableExternallyLinkage();
389 }
390 
391 bool MergeFunctions::runOnModule(Module &M) {
392   if (skipModule(M))
393     return false;
394 
395   bool Changed = false;
396 
397   // All functions in the module, ordered by hash. Functions with a unique
398   // hash value are easily eliminated.
399   std::vector<std::pair<FunctionComparator::FunctionHash, Function *>>
400     HashedFuncs;
401   for (Function &Func : M) {
402     if (isEligibleForMerging(Func)) {
403       HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func});
404     }
405   }
406 
407   std::stable_sort(
408       HashedFuncs.begin(), HashedFuncs.end(),
409       [](const std::pair<FunctionComparator::FunctionHash, Function *> &a,
410          const std::pair<FunctionComparator::FunctionHash, Function *> &b) {
411         return a.first < b.first;
412       });
413 
414   auto S = HashedFuncs.begin();
415   for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
416     // If the hash value matches the previous value or the next one, we must
417     // consider merging it. Otherwise it is dropped and never considered again.
418     if ((I != S && std::prev(I)->first == I->first) ||
419         (std::next(I) != IE && std::next(I)->first == I->first) ) {
420       Deferred.push_back(WeakTrackingVH(I->second));
421     }
422   }
423 
424   do {
425     std::vector<WeakTrackingVH> Worklist;
426     Deferred.swap(Worklist);
427 
428     LLVM_DEBUG(doSanityCheck(Worklist));
429 
430     LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
431     LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
432 
433     // Insert functions and merge them.
434     for (WeakTrackingVH &I : Worklist) {
435       if (!I)
436         continue;
437       Function *F = cast<Function>(I);
438       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
439         Changed |= insert(F);
440       }
441     }
442     LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
443   } while (!Deferred.empty());
444 
445   FnTree.clear();
446   FNodesInTree.clear();
447   GlobalNumbers.clear();
448 
449   return Changed;
450 }
451 
452 // Replace direct callers of Old with New.
453 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
454   Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType());
455   for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) {
456     Use *U = &*UI;
457     ++UI;
458     CallSite CS(U->getUser());
459     if (CS && CS.isCallee(U)) {
460       // Transfer the called function's attributes to the call site. Due to the
461       // bitcast we will 'lose' ABI changing attributes because the 'called
462       // function' is no longer a Function* but the bitcast. Code that looks up
463       // the attributes from the called function will fail.
464 
465       // FIXME: This is not actually true, at least not anymore. The callsite
466       // will always have the same ABI affecting attributes as the callee,
467       // because otherwise the original input has UB. Note that Old and New
468       // always have matching ABI, so no attributes need to be changed.
469       // Transferring other attributes may help other optimizations, but that
470       // should be done uniformly and not in this ad-hoc way.
471       auto &Context = New->getContext();
472       auto NewPAL = New->getAttributes();
473       SmallVector<AttributeSet, 4> NewArgAttrs;
474       for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++)
475         NewArgAttrs.push_back(NewPAL.getParamAttributes(argIdx));
476       // Don't transfer attributes from the function to the callee. Function
477       // attributes typically aren't relevant to the calling convention or ABI.
478       CS.setAttributes(AttributeList::get(Context, /*FnAttrs=*/AttributeSet(),
479                                           NewPAL.getRetAttributes(),
480                                           NewArgAttrs));
481 
482       remove(CS.getInstruction()->getFunction());
483       U->set(BitcastNew);
484     }
485   }
486 }
487 
488 // Helper for writeThunk,
489 // Selects proper bitcast operation,
490 // but a bit simpler then CastInst::getCastOpcode.
491 static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
492   Type *SrcTy = V->getType();
493   if (SrcTy->isStructTy()) {
494     assert(DestTy->isStructTy());
495     assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
496     Value *Result = UndefValue::get(DestTy);
497     for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
498       Value *Element = createCast(
499           Builder, Builder.CreateExtractValue(V, makeArrayRef(I)),
500           DestTy->getStructElementType(I));
501 
502       Result =
503           Builder.CreateInsertValue(Result, Element, makeArrayRef(I));
504     }
505     return Result;
506   }
507   assert(!DestTy->isStructTy());
508   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
509     return Builder.CreateIntToPtr(V, DestTy);
510   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
511     return Builder.CreatePtrToInt(V, DestTy);
512   else
513     return Builder.CreateBitCast(V, DestTy);
514 }
515 
516 // Erase the instructions in PDIUnrelatedWL as they are unrelated to the
517 // parameter debug info, from the entry block.
518 void MergeFunctions::eraseInstsUnrelatedToPDI(
519     std::vector<Instruction *> &PDIUnrelatedWL) {
520   LLVM_DEBUG(
521       dbgs() << " Erasing instructions (in reverse order of appearance in "
522                 "entry block) unrelated to parameter debug info from entry "
523                 "block: {\n");
524   while (!PDIUnrelatedWL.empty()) {
525     Instruction *I = PDIUnrelatedWL.back();
526     LLVM_DEBUG(dbgs() << "  Deleting Instruction: ");
527     LLVM_DEBUG(I->print(dbgs()));
528     LLVM_DEBUG(dbgs() << "\n");
529     I->eraseFromParent();
530     PDIUnrelatedWL.pop_back();
531   }
532   LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
533                        "debug info from entry block. \n");
534 }
535 
536 // Reduce G to its entry block.
537 void MergeFunctions::eraseTail(Function *G) {
538   std::vector<BasicBlock *> WorklistBB;
539   for (Function::iterator BBI = std::next(G->begin()), BBE = G->end();
540        BBI != BBE; ++BBI) {
541     BBI->dropAllReferences();
542     WorklistBB.push_back(&*BBI);
543   }
544   while (!WorklistBB.empty()) {
545     BasicBlock *BB = WorklistBB.back();
546     BB->eraseFromParent();
547     WorklistBB.pop_back();
548   }
549 }
550 
551 // We are interested in the following instructions from the entry block as being
552 // related to parameter debug info:
553 // - @llvm.dbg.declare
554 // - stores from the incoming parameters to locations on the stack-frame
555 // - allocas that create these locations on the stack-frame
556 // - @llvm.dbg.value
557 // - the entry block's terminator
558 // The rest are unrelated to debug info for the parameters; fill up
559 // PDIUnrelatedWL with such instructions.
560 void MergeFunctions::filterInstsUnrelatedToPDI(
561     BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL) {
562   std::set<Instruction *> PDIRelated;
563   for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
564        BI != BIE; ++BI) {
565     if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
566       LLVM_DEBUG(dbgs() << " Deciding: ");
567       LLVM_DEBUG(BI->print(dbgs()));
568       LLVM_DEBUG(dbgs() << "\n");
569       DILocalVariable *DILocVar = DVI->getVariable();
570       if (DILocVar->isParameter()) {
571         LLVM_DEBUG(dbgs() << "  Include (parameter): ");
572         LLVM_DEBUG(BI->print(dbgs()));
573         LLVM_DEBUG(dbgs() << "\n");
574         PDIRelated.insert(&*BI);
575       } else {
576         LLVM_DEBUG(dbgs() << "  Delete (!parameter): ");
577         LLVM_DEBUG(BI->print(dbgs()));
578         LLVM_DEBUG(dbgs() << "\n");
579       }
580     } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
581       LLVM_DEBUG(dbgs() << " Deciding: ");
582       LLVM_DEBUG(BI->print(dbgs()));
583       LLVM_DEBUG(dbgs() << "\n");
584       DILocalVariable *DILocVar = DDI->getVariable();
585       if (DILocVar->isParameter()) {
586         LLVM_DEBUG(dbgs() << "  Parameter: ");
587         LLVM_DEBUG(DILocVar->print(dbgs()));
588         AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
589         if (AI) {
590           LLVM_DEBUG(dbgs() << "  Processing alloca users: ");
591           LLVM_DEBUG(dbgs() << "\n");
592           for (User *U : AI->users()) {
593             if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
594               if (Value *Arg = SI->getValueOperand()) {
595                 if (dyn_cast<Argument>(Arg)) {
596                   LLVM_DEBUG(dbgs() << "  Include: ");
597                   LLVM_DEBUG(AI->print(dbgs()));
598                   LLVM_DEBUG(dbgs() << "\n");
599                   PDIRelated.insert(AI);
600                   LLVM_DEBUG(dbgs() << "   Include (parameter): ");
601                   LLVM_DEBUG(SI->print(dbgs()));
602                   LLVM_DEBUG(dbgs() << "\n");
603                   PDIRelated.insert(SI);
604                   LLVM_DEBUG(dbgs() << "  Include: ");
605                   LLVM_DEBUG(BI->print(dbgs()));
606                   LLVM_DEBUG(dbgs() << "\n");
607                   PDIRelated.insert(&*BI);
608                 } else {
609                   LLVM_DEBUG(dbgs() << "   Delete (!parameter): ");
610                   LLVM_DEBUG(SI->print(dbgs()));
611                   LLVM_DEBUG(dbgs() << "\n");
612                 }
613               }
614             } else {
615               LLVM_DEBUG(dbgs() << "   Defer: ");
616               LLVM_DEBUG(U->print(dbgs()));
617               LLVM_DEBUG(dbgs() << "\n");
618             }
619           }
620         } else {
621           LLVM_DEBUG(dbgs() << "  Delete (alloca NULL): ");
622           LLVM_DEBUG(BI->print(dbgs()));
623           LLVM_DEBUG(dbgs() << "\n");
624         }
625       } else {
626         LLVM_DEBUG(dbgs() << "  Delete (!parameter): ");
627         LLVM_DEBUG(BI->print(dbgs()));
628         LLVM_DEBUG(dbgs() << "\n");
629       }
630     } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
631       LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
632       LLVM_DEBUG(BI->print(dbgs()));
633       LLVM_DEBUG(dbgs() << "\n");
634       PDIRelated.insert(&*BI);
635     } else {
636       LLVM_DEBUG(dbgs() << " Defer: ");
637       LLVM_DEBUG(BI->print(dbgs()));
638       LLVM_DEBUG(dbgs() << "\n");
639     }
640   }
641   LLVM_DEBUG(
642       dbgs()
643       << " Report parameter debug info related/related instructions: {\n");
644   for (BasicBlock::iterator BI = GEntryBlock->begin(), BE = GEntryBlock->end();
645        BI != BE; ++BI) {
646 
647     Instruction *I = &*BI;
648     if (PDIRelated.find(I) == PDIRelated.end()) {
649       LLVM_DEBUG(dbgs() << "  !PDIRelated: ");
650       LLVM_DEBUG(I->print(dbgs()));
651       LLVM_DEBUG(dbgs() << "\n");
652       PDIUnrelatedWL.push_back(I);
653     } else {
654       LLVM_DEBUG(dbgs() << "   PDIRelated: ");
655       LLVM_DEBUG(I->print(dbgs()));
656       LLVM_DEBUG(dbgs() << "\n");
657     }
658   }
659   LLVM_DEBUG(dbgs() << " }\n");
660 }
661 
662 /// Whether this function may be replaced by a forwarding thunk.
663 static bool canCreateThunkFor(Function *F) {
664   if (F->isVarArg())
665     return false;
666 
667   // Don't merge tiny functions using a thunk, since it can just end up
668   // making the function larger.
669   if (F->size() == 1) {
670     if (F->front().size() <= 2) {
671       LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
672                         << " is too small to bother creating a thunk for\n");
673       return false;
674     }
675   }
676   return true;
677 }
678 
679 // Replace G with a simple tail call to bitcast(F). Also (unless
680 // MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
681 // delete G. Under MergeFunctionsPDI, we use G itself for creating
682 // the thunk as we preserve the debug info (and associated instructions)
683 // from G's entry block pertaining to G's incoming arguments which are
684 // passed on as corresponding arguments in the call that G makes to F.
685 // For better debugability, under MergeFunctionsPDI, we do not modify G's
686 // call sites to point to F even when within the same translation unit.
687 void MergeFunctions::writeThunk(Function *F, Function *G) {
688   BasicBlock *GEntryBlock = nullptr;
689   std::vector<Instruction *> PDIUnrelatedWL;
690   BasicBlock *BB = nullptr;
691   Function *NewG = nullptr;
692   if (MergeFunctionsPDI) {
693     LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
694                          "function as thunk; retain original: "
695                       << G->getName() << "()\n");
696     GEntryBlock = &G->getEntryBlock();
697     LLVM_DEBUG(
698         dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
699                   "debug info for "
700                << G->getName() << "() {\n");
701     filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL);
702     GEntryBlock->getTerminator()->eraseFromParent();
703     BB = GEntryBlock;
704   } else {
705     NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
706                             G->getAddressSpace(), "", G->getParent());
707     BB = BasicBlock::Create(F->getContext(), "", NewG);
708   }
709 
710   IRBuilder<> Builder(BB);
711   Function *H = MergeFunctionsPDI ? G : NewG;
712   SmallVector<Value *, 16> Args;
713   unsigned i = 0;
714   FunctionType *FFTy = F->getFunctionType();
715   for (Argument &AI : H->args()) {
716     Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
717     ++i;
718   }
719 
720   CallInst *CI = Builder.CreateCall(F, Args);
721   ReturnInst *RI = nullptr;
722   CI->setTailCall();
723   CI->setCallingConv(F->getCallingConv());
724   CI->setAttributes(F->getAttributes());
725   if (H->getReturnType()->isVoidTy()) {
726     RI = Builder.CreateRetVoid();
727   } else {
728     RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
729   }
730 
731   if (MergeFunctionsPDI) {
732     DISubprogram *DIS = G->getSubprogram();
733     if (DIS) {
734       DebugLoc CIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
735       DebugLoc RIDbgLoc = DebugLoc::get(DIS->getScopeLine(), 0, DIS);
736       CI->setDebugLoc(CIDbgLoc);
737       RI->setDebugLoc(RIDbgLoc);
738     } else {
739       LLVM_DEBUG(
740           dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
741                  << G->getName() << "()\n");
742     }
743     eraseTail(G);
744     eraseInstsUnrelatedToPDI(PDIUnrelatedWL);
745     LLVM_DEBUG(
746         dbgs() << "} // End of parameter related debug info filtering for: "
747                << G->getName() << "()\n");
748   } else {
749     NewG->copyAttributesFrom(G);
750     NewG->takeName(G);
751     removeUsers(G);
752     G->replaceAllUsesWith(NewG);
753     G->eraseFromParent();
754   }
755 
756   LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
757   ++NumThunksWritten;
758 }
759 
760 // Whether this function may be replaced by an alias
761 static bool canCreateAliasFor(Function *F) {
762   if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
763     return false;
764 
765   // We should only see linkages supported by aliases here
766   assert(F->hasLocalLinkage() || F->hasExternalLinkage()
767       || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
768   return true;
769 }
770 
771 // Replace G with an alias to F (deleting function G)
772 void MergeFunctions::writeAlias(Function *F, Function *G) {
773   Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
774   PointerType *PtrType = G->getType();
775   auto *GA = GlobalAlias::create(
776       PtrType->getElementType(), PtrType->getAddressSpace(),
777       G->getLinkage(), "", BitcastF, G->getParent());
778 
779   F->setAlignment(std::max(F->getAlignment(), G->getAlignment()));
780   GA->takeName(G);
781   GA->setVisibility(G->getVisibility());
782   GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
783 
784   removeUsers(G);
785   G->replaceAllUsesWith(GA);
786   G->eraseFromParent();
787 
788   LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
789   ++NumAliasesWritten;
790 }
791 
792 // Replace G with an alias to F if possible, or a thunk to F if
793 // profitable. Returns false if neither is the case.
794 bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
795   if (canCreateAliasFor(G)) {
796     writeAlias(F, G);
797     return true;
798   }
799   if (canCreateThunkFor(F)) {
800     writeThunk(F, G);
801     return true;
802   }
803   return false;
804 }
805 
806 // Merge two equivalent functions. Upon completion, Function G is deleted.
807 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
808   if (F->isInterposable()) {
809     assert(G->isInterposable());
810 
811     // Both writeThunkOrAlias() calls below must succeed, either because we can
812     // create aliases for G and NewF, or because a thunk for F is profitable.
813     // F here has the same signature as NewF below, so that's what we check.
814     if (!canCreateThunkFor(F) &&
815         (!canCreateAliasFor(F) || !canCreateAliasFor(G)))
816       return;
817 
818     // Make them both thunks to the same internal function.
819     Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
820                                       F->getAddressSpace(), "", F->getParent());
821     NewF->copyAttributesFrom(F);
822     NewF->takeName(F);
823     removeUsers(F);
824     F->replaceAllUsesWith(NewF);
825 
826     unsigned MaxAlignment = std::max(G->getAlignment(), NewF->getAlignment());
827 
828     writeThunkOrAlias(F, G);
829     writeThunkOrAlias(F, NewF);
830 
831     F->setAlignment(MaxAlignment);
832     F->setLinkage(GlobalValue::PrivateLinkage);
833     ++NumDoubleWeak;
834     ++NumFunctionsMerged;
835   } else {
836     // For better debugability, under MergeFunctionsPDI, we do not modify G's
837     // call sites to point to F even when within the same translation unit.
838     if (!G->isInterposable() && !MergeFunctionsPDI) {
839       if (G->hasGlobalUnnamedAddr()) {
840         // G might have been a key in our GlobalNumberState, and it's illegal
841         // to replace a key in ValueMap<GlobalValue *> with a non-global.
842         GlobalNumbers.erase(G);
843         // If G's address is not significant, replace it entirely.
844         Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType());
845         removeUsers(G);
846         G->replaceAllUsesWith(BitcastF);
847       } else {
848         // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
849         // above).
850         replaceDirectCallers(G, F);
851       }
852     }
853 
854     // If G was internal then we may have replaced all uses of G with F. If so,
855     // stop here and delete G. There's no need for a thunk. (See note on
856     // MergeFunctionsPDI above).
857     if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
858       G->eraseFromParent();
859       ++NumFunctionsMerged;
860       return;
861     }
862 
863     if (writeThunkOrAlias(F, G)) {
864       ++NumFunctionsMerged;
865     }
866   }
867 }
868 
869 /// Replace function F by function G.
870 void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
871                                            Function *G) {
872   Function *F = FN.getFunc();
873   assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
874          "The two functions must be equal");
875 
876   auto I = FNodesInTree.find(F);
877   assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
878   assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
879 
880   FnTreeType::iterator IterToFNInFnTree = I->second;
881   assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
882   // Remove F -> FN and insert G -> FN
883   FNodesInTree.erase(I);
884   FNodesInTree.insert({G, IterToFNInFnTree});
885   // Replace F with G in FN, which is stored inside the FnTree.
886   FN.replaceBy(G);
887 }
888 
889 // Ordering for functions that are equal under FunctionComparator
890 static bool isFuncOrderCorrect(const Function *F, const Function *G) {
891   if (F->isInterposable() != G->isInterposable()) {
892     // Strong before weak, because the weak function may call the strong
893     // one, but not the other way around.
894     return !F->isInterposable();
895   }
896   if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
897     // External before local, because we definitely have to keep the external
898     // function, but may be able to drop the local one.
899     return !F->hasLocalLinkage();
900   }
901   // Impose a total order (by name) on the replacement of functions. This is
902   // important when operating on more than one module independently to prevent
903   // cycles of thunks calling each other when the modules are linked together.
904   return F->getName() <= G->getName();
905 }
906 
907 // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
908 // that was already inserted.
909 bool MergeFunctions::insert(Function *NewFunction) {
910   std::pair<FnTreeType::iterator, bool> Result =
911       FnTree.insert(FunctionNode(NewFunction));
912 
913   if (Result.second) {
914     assert(FNodesInTree.count(NewFunction) == 0);
915     FNodesInTree.insert({NewFunction, Result.first});
916     LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
917                       << '\n');
918     return false;
919   }
920 
921   const FunctionNode &OldF = *Result.first;
922 
923   if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
924     // Swap the two functions.
925     Function *F = OldF.getFunc();
926     replaceFunctionInTree(*Result.first, NewFunction);
927     NewFunction = F;
928     assert(OldF.getFunc() != F && "Must have swapped the functions.");
929   }
930 
931   LLVM_DEBUG(dbgs() << "  " << OldF.getFunc()->getName()
932                     << " == " << NewFunction->getName() << '\n');
933 
934   Function *DeleteF = NewFunction;
935   mergeTwoFunctions(OldF.getFunc(), DeleteF);
936   return true;
937 }
938 
939 // Remove a function from FnTree. If it was already in FnTree, add
940 // it to Deferred so that we'll look at it in the next round.
941 void MergeFunctions::remove(Function *F) {
942   auto I = FNodesInTree.find(F);
943   if (I != FNodesInTree.end()) {
944     LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
945     FnTree.erase(I->second);
946     // I->second has been invalidated, remove it from the FNodesInTree map to
947     // preserve the invariant.
948     FNodesInTree.erase(I);
949     Deferred.emplace_back(F);
950   }
951 }
952 
953 // For each instruction used by the value, remove() the function that contains
954 // the instruction. This should happen right before a call to RAUW.
955 void MergeFunctions::removeUsers(Value *V) {
956   std::vector<Value *> Worklist;
957   Worklist.push_back(V);
958   SmallPtrSet<Value*, 8> Visited;
959   Visited.insert(V);
960   while (!Worklist.empty()) {
961     Value *V = Worklist.back();
962     Worklist.pop_back();
963 
964     for (User *U : V->users()) {
965       if (Instruction *I = dyn_cast<Instruction>(U)) {
966         remove(I->getFunction());
967       } else if (isa<GlobalValue>(U)) {
968         // do nothing
969       } else if (Constant *C = dyn_cast<Constant>(U)) {
970         for (User *UU : C->users()) {
971           if (!Visited.insert(UU).second)
972             Worklist.push_back(UU);
973         }
974       }
975     }
976   }
977 }
978