xref: /llvm-project/llvm/lib/Transforms/IPO/MergeFunctions.cpp (revision 98ea1a81a28a6dd36941456c8ab4ce46f665f57a)
1 //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass looks for equivalent functions that are mergable and folds them.
10 //
11 // Order relation is defined on set of functions. It was made through
12 // special function comparison procedure that returns
13 // 0 when functions are equal,
14 // -1 when Left function is less than right function, and
15 // 1 for opposite case. We need total-ordering, so we need to maintain
16 // four properties on the functions set:
17 // a <= a (reflexivity)
18 // if a <= b and b <= a then a = b (antisymmetry)
19 // if a <= b and b <= c then a <= c (transitivity).
20 // for all a and b: a <= b or b <= a (totality).
21 //
22 // Comparison iterates through each instruction in each basic block.
23 // Functions are kept on binary tree. For each new function F we perform
24 // lookup in binary tree.
25 // In practice it works the following way:
26 // -- We define Function* container class with custom "operator<" (FunctionPtr).
27 // -- "FunctionPtr" instances are stored in std::set collection, so every
28 //    std::set::insert operation will give you result in log(N) time.
29 //
30 // As an optimization, a hash of the function structure is calculated first, and
31 // two functions are only compared if they have the same hash. This hash is
32 // cheap to compute, and has the property that if function F == G according to
33 // the comparison function, then hash(F) == hash(G). This consistency property
34 // is critical to ensuring all possible merging opportunities are exploited.
35 // Collisions in the hash affect the speed of the pass but not the correctness
36 // or determinism of the resulting transformation.
37 //
38 // When a match is found the functions are folded. If both functions are
39 // overridable, we move the functionality into a new internal function and
40 // leave two overridable thunks to it.
41 //
42 //===----------------------------------------------------------------------===//
43 //
44 // Future work:
45 //
46 // * virtual functions.
47 //
48 // Many functions have their address taken by the virtual function table for
49 // the object they belong to. However, as long as it's only used for a lookup
50 // and call, this is irrelevant, and we'd like to fold such functions.
51 //
52 // * be smarter about bitcasts.
53 //
54 // In order to fold functions, we will sometimes add either bitcast instructions
55 // or bitcast constant expressions. Unfortunately, this can confound further
56 // analysis since the two functions differ where one has a bitcast and the
57 // other doesn't. We should learn to look through bitcasts.
58 //
59 // * Compare complex types with pointer types inside.
60 // * Compare cross-reference cases.
61 // * Compare complex expressions.
62 //
63 // All the three issues above could be described as ability to prove that
64 // fA == fB == fC == fE == fF == fG in example below:
65 //
66 //  void fA() {
67 //    fB();
68 //  }
69 //  void fB() {
70 //    fA();
71 //  }
72 //
73 //  void fE() {
74 //    fF();
75 //  }
76 //  void fF() {
77 //    fG();
78 //  }
79 //  void fG() {
80 //    fE();
81 //  }
82 //
83 // Simplest cross-reference case (fA <--> fB) was implemented in previous
84 // versions of MergeFunctions, though it presented only in two function pairs
85 // in test-suite (that counts >50k functions)
86 // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
87 // could cover much more cases.
88 //
89 //===----------------------------------------------------------------------===//
90 
91 #include "llvm/Transforms/IPO/MergeFunctions.h"
92 #include "llvm/ADT/ArrayRef.h"
93 #include "llvm/ADT/SmallVector.h"
94 #include "llvm/ADT/Statistic.h"
95 #include "llvm/IR/Argument.h"
96 #include "llvm/IR/BasicBlock.h"
97 #include "llvm/IR/Constants.h"
98 #include "llvm/IR/DebugInfoMetadata.h"
99 #include "llvm/IR/DebugLoc.h"
100 #include "llvm/IR/DerivedTypes.h"
101 #include "llvm/IR/Function.h"
102 #include "llvm/IR/GlobalValue.h"
103 #include "llvm/IR/IRBuilder.h"
104 #include "llvm/IR/InstrTypes.h"
105 #include "llvm/IR/Instruction.h"
106 #include "llvm/IR/Instructions.h"
107 #include "llvm/IR/IntrinsicInst.h"
108 #include "llvm/IR/Module.h"
109 #include "llvm/IR/StructuralHash.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/ValueHandle.h"
115 #include "llvm/Support/Casting.h"
116 #include "llvm/Support/CommandLine.h"
117 #include "llvm/Support/Debug.h"
118 #include "llvm/Support/raw_ostream.h"
119 #include "llvm/Transforms/IPO.h"
120 #include "llvm/Transforms/Utils/FunctionComparator.h"
121 #include "llvm/Transforms/Utils/ModuleUtils.h"
122 #include <algorithm>
123 #include <cassert>
124 #include <iterator>
125 #include <set>
126 #include <utility>
127 #include <vector>
128 
129 using namespace llvm;
130 
131 #define DEBUG_TYPE "mergefunc"
132 
133 STATISTIC(NumFunctionsMerged, "Number of functions merged");
134 STATISTIC(NumThunksWritten, "Number of thunks generated");
135 STATISTIC(NumAliasesWritten, "Number of aliases generated");
136 STATISTIC(NumDoubleWeak, "Number of new functions created");
137 
138 static cl::opt<unsigned> NumFunctionsForVerificationCheck(
139     "mergefunc-verify",
140     cl::desc("How many functions in a module could be used for "
141              "MergeFunctions to pass a basic correctness check. "
142              "'0' disables this check. Works only with '-debug' key."),
143     cl::init(0), cl::Hidden);
144 
145 // Under option -mergefunc-preserve-debug-info we:
146 // - Do not create a new function for a thunk.
147 // - Retain the debug info for a thunk's parameters (and associated
148 //   instructions for the debug info) from the entry block.
149 //   Note: -debug will display the algorithm at work.
150 // - Create debug-info for the call (to the shared implementation) made by
151 //   a thunk and its return value.
152 // - Erase the rest of the function, retaining the (minimally sized) entry
153 //   block to create a thunk.
154 // - Preserve a thunk's call site to point to the thunk even when both occur
155 //   within the same translation unit, to aid debugability. Note that this
156 //   behaviour differs from the underlying -mergefunc implementation which
157 //   modifies the thunk's call site to point to the shared implementation
158 //   when both occur within the same translation unit.
159 static cl::opt<bool>
160     MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
161                       cl::init(false),
162                       cl::desc("Preserve debug info in thunk when mergefunc "
163                                "transformations are made."));
164 
165 static cl::opt<bool>
166     MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
167                           cl::init(false),
168                           cl::desc("Allow mergefunc to create aliases"));
169 
170 namespace {
171 
172 class FunctionNode {
173   mutable AssertingVH<Function> F;
174   stable_hash Hash;
175 
176 public:
177   // Note the hash is recalculated potentially multiple times, but it is cheap.
178   FunctionNode(Function *F) : F(F), Hash(StructuralHash(*F)) {}
179 
180   Function *getFunc() const { return F; }
181   stable_hash getHash() const { return Hash; }
182 
183   /// Replace the reference to the function F by the function G, assuming their
184   /// implementations are equal.
185   void replaceBy(Function *G) const {
186     F = G;
187   }
188 };
189 
190 /// MergeFunctions finds functions which will generate identical machine code,
191 /// by considering all pointer types to be equivalent. Once identified,
192 /// MergeFunctions will fold them by replacing a call to one to a call to a
193 /// bitcast of the other.
194 class MergeFunctions {
195 public:
196   MergeFunctions() : FnTree(FunctionNodeCmp(&GlobalNumbers)) {
197   }
198 
199   bool runOnModule(Module &M);
200 
201 private:
202   // The function comparison operator is provided here so that FunctionNodes do
203   // not need to become larger with another pointer.
204   class FunctionNodeCmp {
205     GlobalNumberState* GlobalNumbers;
206 
207   public:
208     FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
209 
210     bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
211       // Order first by hashes, then full function comparison.
212       if (LHS.getHash() != RHS.getHash())
213         return LHS.getHash() < RHS.getHash();
214       FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
215       return FCmp.compare() < 0;
216     }
217   };
218   using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
219 
220   GlobalNumberState GlobalNumbers;
221 
222   /// A work queue of functions that may have been modified and should be
223   /// analyzed again.
224   std::vector<WeakTrackingVH> Deferred;
225 
226   /// Set of values marked as used in llvm.used and llvm.compiler.used.
227   SmallPtrSet<GlobalValue *, 4> Used;
228 
229 #ifndef NDEBUG
230   /// Checks the rules of order relation introduced among functions set.
231   /// Returns true, if check has been passed, and false if failed.
232   bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
233 #endif
234 
235   /// Insert a ComparableFunction into the FnTree, or merge it away if it's
236   /// equal to one that's already present.
237   bool insert(Function *NewFunction);
238 
239   /// Remove a Function from the FnTree and queue it up for a second sweep of
240   /// analysis.
241   void remove(Function *F);
242 
243   /// Find the functions that use this Value and remove them from FnTree and
244   /// queue the functions.
245   void removeUsers(Value *V);
246 
247   /// Replace all direct calls of Old with calls of New. Will bitcast New if
248   /// necessary to make types match.
249   void replaceDirectCallers(Function *Old, Function *New);
250 
251   /// Merge two equivalent functions. Upon completion, G may be deleted, or may
252   /// be converted into a thunk. In either case, it should never be visited
253   /// again.
254   void mergeTwoFunctions(Function *F, Function *G);
255 
256   /// Fill PDIUnrelatedWL with instructions from the entry block that are
257   /// unrelated to parameter related debug info.
258   /// \param PDVRUnrelatedWL The equivalent non-intrinsic debug records.
259   void
260   filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
261                             std::vector<Instruction *> &PDIUnrelatedWL,
262                             std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
263 
264   /// Erase the rest of the CFG (i.e. barring the entry block).
265   void eraseTail(Function *G);
266 
267   /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
268   /// parameter debug info, from the entry block.
269   /// \param PDVRUnrelatedWL contains the equivalent set of non-instruction
270   /// debug-info records.
271   void
272   eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL,
273                            std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
274 
275   /// Replace G with a simple tail call to bitcast(F). Also (unless
276   /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
277   /// delete G.
278   void writeThunk(Function *F, Function *G);
279 
280   // Replace G with an alias to F (deleting function G)
281   void writeAlias(Function *F, Function *G);
282 
283   // Replace G with an alias to F if possible, or a thunk to F if possible.
284   // Returns false if neither is the case.
285   bool writeThunkOrAlias(Function *F, Function *G);
286 
287   /// Replace function F with function G in the function tree.
288   void replaceFunctionInTree(const FunctionNode &FN, Function *G);
289 
290   /// The set of all distinct functions. Use the insert() and remove() methods
291   /// to modify it. The map allows efficient lookup and deferring of Functions.
292   FnTreeType FnTree;
293 
294   // Map functions to the iterators of the FunctionNode which contains them
295   // in the FnTree. This must be updated carefully whenever the FnTree is
296   // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
297   // dangling iterators into FnTree. The invariant that preserves this is that
298   // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
299   DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
300 };
301 } // end anonymous namespace
302 
303 PreservedAnalyses MergeFunctionsPass::run(Module &M,
304                                           ModuleAnalysisManager &AM) {
305   MergeFunctions MF;
306   if (!MF.runOnModule(M))
307     return PreservedAnalyses::all();
308   return PreservedAnalyses::none();
309 }
310 
311 #ifndef NDEBUG
312 bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
313   if (const unsigned Max = NumFunctionsForVerificationCheck) {
314     unsigned TripleNumber = 0;
315     bool Valid = true;
316 
317     dbgs() << "MERGEFUNC-VERIFY: Started for first " << Max << " functions.\n";
318 
319     unsigned i = 0;
320     for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
321                                                E = Worklist.end();
322          I != E && i < Max; ++I, ++i) {
323       unsigned j = i;
324       for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
325            ++J, ++j) {
326         Function *F1 = cast<Function>(*I);
327         Function *F2 = cast<Function>(*J);
328         int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
329         int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
330 
331         // If F1 <= F2, then F2 >= F1, otherwise report failure.
332         if (Res1 != -Res2) {
333           dbgs() << "MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
334                  << "\n";
335           dbgs() << *F1 << '\n' << *F2 << '\n';
336           Valid = false;
337         }
338 
339         if (Res1 == 0)
340           continue;
341 
342         unsigned k = j;
343         for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
344              ++k, ++K, ++TripleNumber) {
345           if (K == J)
346             continue;
347 
348           Function *F3 = cast<Function>(*K);
349           int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
350           int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
351 
352           bool Transitive = true;
353 
354           if (Res1 != 0 && Res1 == Res4) {
355             // F1 > F2, F2 > F3 => F1 > F3
356             Transitive = Res3 == Res1;
357           } else if (Res3 != 0 && Res3 == -Res4) {
358             // F1 > F3, F3 > F2 => F1 > F2
359             Transitive = Res3 == Res1;
360           } else if (Res4 != 0 && -Res3 == Res4) {
361             // F2 > F3, F3 > F1 => F2 > F1
362             Transitive = Res4 == -Res1;
363           }
364 
365           if (!Transitive) {
366             dbgs() << "MERGEFUNC-VERIFY: Non-transitive; triple: "
367                    << TripleNumber << "\n";
368             dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
369                    << Res4 << "\n";
370             dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
371             Valid = false;
372           }
373         }
374       }
375     }
376 
377     dbgs() << "MERGEFUNC-VERIFY: " << (Valid ? "Passed." : "Failed.") << "\n";
378     return Valid;
379   }
380   return true;
381 }
382 #endif
383 
384 /// Check whether \p F has an intrinsic which references
385 /// distinct metadata as an operand. The most common
386 /// instance of this would be CFI checks for function-local types.
387 static bool hasDistinctMetadataIntrinsic(const Function &F) {
388   for (const BasicBlock &BB : F) {
389     for (const Instruction &I : BB.instructionsWithoutDebug()) {
390       if (!isa<IntrinsicInst>(&I))
391         continue;
392 
393       for (Value *Op : I.operands()) {
394         auto *MDL = dyn_cast<MetadataAsValue>(Op);
395         if (!MDL)
396           continue;
397         if (MDNode *N = dyn_cast<MDNode>(MDL->getMetadata()))
398           if (N->isDistinct())
399             return true;
400       }
401     }
402   }
403   return false;
404 }
405 
406 /// Check whether \p F is eligible for function merging.
407 static bool isEligibleForMerging(Function &F) {
408   return !F.isDeclaration() && !F.hasAvailableExternallyLinkage() &&
409          !hasDistinctMetadataIntrinsic(F);
410 }
411 
412 bool MergeFunctions::runOnModule(Module &M) {
413   bool Changed = false;
414 
415   SmallVector<GlobalValue *, 4> UsedV;
416   collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/false);
417   collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/true);
418   Used.insert(UsedV.begin(), UsedV.end());
419 
420   // All functions in the module, ordered by hash. Functions with a unique
421   // hash value are easily eliminated.
422   std::vector<std::pair<stable_hash, Function *>> HashedFuncs;
423   for (Function &Func : M) {
424     if (isEligibleForMerging(Func)) {
425       HashedFuncs.push_back({StructuralHash(Func), &Func});
426     }
427   }
428 
429   llvm::stable_sort(HashedFuncs, less_first());
430 
431   auto S = HashedFuncs.begin();
432   for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
433     // If the hash value matches the previous value or the next one, we must
434     // consider merging it. Otherwise it is dropped and never considered again.
435     if ((I != S && std::prev(I)->first == I->first) ||
436         (std::next(I) != IE && std::next(I)->first == I->first) ) {
437       Deferred.push_back(WeakTrackingVH(I->second));
438     }
439   }
440 
441   do {
442     std::vector<WeakTrackingVH> Worklist;
443     Deferred.swap(Worklist);
444 
445     LLVM_DEBUG(doFunctionalCheck(Worklist));
446 
447     LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
448     LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
449 
450     // Insert functions and merge them.
451     for (WeakTrackingVH &I : Worklist) {
452       if (!I)
453         continue;
454       Function *F = cast<Function>(I);
455       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
456         Changed |= insert(F);
457       }
458     }
459     LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
460   } while (!Deferred.empty());
461 
462   FnTree.clear();
463   FNodesInTree.clear();
464   GlobalNumbers.clear();
465   Used.clear();
466 
467   return Changed;
468 }
469 
470 // Replace direct callers of Old with New.
471 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
472   for (Use &U : llvm::make_early_inc_range(Old->uses())) {
473     CallBase *CB = dyn_cast<CallBase>(U.getUser());
474     if (CB && CB->isCallee(&U)) {
475       // Do not copy attributes from the called function to the call-site.
476       // Function comparison ensures that the attributes are the same up to
477       // type congruences in byval(), in which case we need to keep the byval
478       // type of the call-site, not the callee function.
479       remove(CB->getFunction());
480       U.set(New);
481     }
482   }
483 }
484 
485 // Helper for writeThunk,
486 // Selects proper bitcast operation,
487 // but a bit simpler then CastInst::getCastOpcode.
488 static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
489   Type *SrcTy = V->getType();
490   if (SrcTy->isStructTy()) {
491     assert(DestTy->isStructTy());
492     assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
493     Value *Result = PoisonValue::get(DestTy);
494     for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
495       Value *Element =
496           createCast(Builder, Builder.CreateExtractValue(V, ArrayRef(I)),
497                      DestTy->getStructElementType(I));
498 
499       Result = Builder.CreateInsertValue(Result, Element, ArrayRef(I));
500     }
501     return Result;
502   }
503   assert(!DestTy->isStructTy());
504   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
505     return Builder.CreateIntToPtr(V, DestTy);
506   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
507     return Builder.CreatePtrToInt(V, DestTy);
508   else
509     return Builder.CreateBitCast(V, DestTy);
510 }
511 
512 // Erase the instructions in PDIUnrelatedWL as they are unrelated to the
513 // parameter debug info, from the entry block.
514 void MergeFunctions::eraseInstsUnrelatedToPDI(
515     std::vector<Instruction *> &PDIUnrelatedWL,
516     std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
517   LLVM_DEBUG(
518       dbgs() << " Erasing instructions (in reverse order of appearance in "
519                 "entry block) unrelated to parameter debug info from entry "
520                 "block: {\n");
521   while (!PDIUnrelatedWL.empty()) {
522     Instruction *I = PDIUnrelatedWL.back();
523     LLVM_DEBUG(dbgs() << "  Deleting Instruction: ");
524     LLVM_DEBUG(I->print(dbgs()));
525     LLVM_DEBUG(dbgs() << "\n");
526     I->eraseFromParent();
527     PDIUnrelatedWL.pop_back();
528   }
529 
530   while (!PDVRUnrelatedWL.empty()) {
531     DbgVariableRecord *DVR = PDVRUnrelatedWL.back();
532     LLVM_DEBUG(dbgs() << "  Deleting DbgVariableRecord ");
533     LLVM_DEBUG(DVR->print(dbgs()));
534     LLVM_DEBUG(dbgs() << "\n");
535     DVR->eraseFromParent();
536     PDVRUnrelatedWL.pop_back();
537   }
538 
539   LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
540                        "debug info from entry block. \n");
541 }
542 
543 // Reduce G to its entry block.
544 void MergeFunctions::eraseTail(Function *G) {
545   std::vector<BasicBlock *> WorklistBB;
546   for (BasicBlock &BB : drop_begin(*G)) {
547     BB.dropAllReferences();
548     WorklistBB.push_back(&BB);
549   }
550   while (!WorklistBB.empty()) {
551     BasicBlock *BB = WorklistBB.back();
552     BB->eraseFromParent();
553     WorklistBB.pop_back();
554   }
555 }
556 
557 // We are interested in the following instructions from the entry block as being
558 // related to parameter debug info:
559 // - @llvm.dbg.declare
560 // - stores from the incoming parameters to locations on the stack-frame
561 // - allocas that create these locations on the stack-frame
562 // - @llvm.dbg.value
563 // - the entry block's terminator
564 // The rest are unrelated to debug info for the parameters; fill up
565 // PDIUnrelatedWL with such instructions.
566 void MergeFunctions::filterInstsUnrelatedToPDI(
567     BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL,
568     std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
569   std::set<Instruction *> PDIRelated;
570   std::set<DbgVariableRecord *> PDVRRelated;
571 
572   // Work out whether a dbg.value intrinsic or an equivalent DbgVariableRecord
573   // is a parameter to be preserved.
574   auto ExamineDbgValue = [](auto *DbgVal, auto &Container) {
575     LLVM_DEBUG(dbgs() << " Deciding: ");
576     LLVM_DEBUG(DbgVal->print(dbgs()));
577     LLVM_DEBUG(dbgs() << "\n");
578     DILocalVariable *DILocVar = DbgVal->getVariable();
579     if (DILocVar->isParameter()) {
580       LLVM_DEBUG(dbgs() << "  Include (parameter): ");
581       LLVM_DEBUG(DbgVal->print(dbgs()));
582       LLVM_DEBUG(dbgs() << "\n");
583       Container.insert(DbgVal);
584     } else {
585       LLVM_DEBUG(dbgs() << "  Delete (!parameter): ");
586       LLVM_DEBUG(DbgVal->print(dbgs()));
587       LLVM_DEBUG(dbgs() << "\n");
588     }
589   };
590 
591   auto ExamineDbgDeclare = [&PDIRelated](auto *DbgDecl, auto &Container) {
592     LLVM_DEBUG(dbgs() << " Deciding: ");
593     LLVM_DEBUG(DbgDecl->print(dbgs()));
594     LLVM_DEBUG(dbgs() << "\n");
595     DILocalVariable *DILocVar = DbgDecl->getVariable();
596     if (DILocVar->isParameter()) {
597       LLVM_DEBUG(dbgs() << "  Parameter: ");
598       LLVM_DEBUG(DILocVar->print(dbgs()));
599       AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DbgDecl->getAddress());
600       if (AI) {
601         LLVM_DEBUG(dbgs() << "  Processing alloca users: ");
602         LLVM_DEBUG(dbgs() << "\n");
603         for (User *U : AI->users()) {
604           if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
605             if (Value *Arg = SI->getValueOperand()) {
606               if (isa<Argument>(Arg)) {
607                 LLVM_DEBUG(dbgs() << "  Include: ");
608                 LLVM_DEBUG(AI->print(dbgs()));
609                 LLVM_DEBUG(dbgs() << "\n");
610                 PDIRelated.insert(AI);
611                 LLVM_DEBUG(dbgs() << "   Include (parameter): ");
612                 LLVM_DEBUG(SI->print(dbgs()));
613                 LLVM_DEBUG(dbgs() << "\n");
614                 PDIRelated.insert(SI);
615                 LLVM_DEBUG(dbgs() << "  Include: ");
616                 LLVM_DEBUG(DbgDecl->print(dbgs()));
617                 LLVM_DEBUG(dbgs() << "\n");
618                 Container.insert(DbgDecl);
619               } else {
620                 LLVM_DEBUG(dbgs() << "   Delete (!parameter): ");
621                 LLVM_DEBUG(SI->print(dbgs()));
622                 LLVM_DEBUG(dbgs() << "\n");
623               }
624             }
625           } else {
626             LLVM_DEBUG(dbgs() << "   Defer: ");
627             LLVM_DEBUG(U->print(dbgs()));
628             LLVM_DEBUG(dbgs() << "\n");
629           }
630         }
631       } else {
632         LLVM_DEBUG(dbgs() << "  Delete (alloca NULL): ");
633         LLVM_DEBUG(DbgDecl->print(dbgs()));
634         LLVM_DEBUG(dbgs() << "\n");
635       }
636     } else {
637       LLVM_DEBUG(dbgs() << "  Delete (!parameter): ");
638       LLVM_DEBUG(DbgDecl->print(dbgs()));
639       LLVM_DEBUG(dbgs() << "\n");
640     }
641   };
642 
643   for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
644        BI != BIE; ++BI) {
645     // Examine DbgVariableRecords as they happen "before" the instruction. Are
646     // they connected to parameters?
647     for (DbgVariableRecord &DVR : filterDbgVars(BI->getDbgRecordRange())) {
648       if (DVR.isDbgValue() || DVR.isDbgAssign()) {
649         ExamineDbgValue(&DVR, PDVRRelated);
650       } else {
651         assert(DVR.isDbgDeclare());
652         ExamineDbgDeclare(&DVR, PDVRRelated);
653       }
654     }
655 
656     if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
657       ExamineDbgValue(DVI, PDIRelated);
658     } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
659       ExamineDbgDeclare(DDI, PDIRelated);
660     } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
661       LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
662       LLVM_DEBUG(BI->print(dbgs()));
663       LLVM_DEBUG(dbgs() << "\n");
664       PDIRelated.insert(&*BI);
665     } else {
666       LLVM_DEBUG(dbgs() << " Defer: ");
667       LLVM_DEBUG(BI->print(dbgs()));
668       LLVM_DEBUG(dbgs() << "\n");
669     }
670   }
671   LLVM_DEBUG(
672       dbgs()
673       << " Report parameter debug info related/related instructions: {\n");
674 
675   auto IsPDIRelated = [](auto *Rec, auto &Container, auto &UnrelatedCont) {
676     if (Container.find(Rec) == Container.end()) {
677       LLVM_DEBUG(dbgs() << "  !PDIRelated: ");
678       LLVM_DEBUG(Rec->print(dbgs()));
679       LLVM_DEBUG(dbgs() << "\n");
680       UnrelatedCont.push_back(Rec);
681     } else {
682       LLVM_DEBUG(dbgs() << "   PDIRelated: ");
683       LLVM_DEBUG(Rec->print(dbgs()));
684       LLVM_DEBUG(dbgs() << "\n");
685     }
686   };
687 
688   // Collect the set of unrelated instructions and debug records.
689   for (Instruction &I : *GEntryBlock) {
690     for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
691       IsPDIRelated(&DVR, PDVRRelated, PDVRUnrelatedWL);
692     IsPDIRelated(&I, PDIRelated, PDIUnrelatedWL);
693   }
694   LLVM_DEBUG(dbgs() << " }\n");
695 }
696 
697 /// Whether this function may be replaced by a forwarding thunk.
698 static bool canCreateThunkFor(Function *F) {
699   if (F->isVarArg())
700     return false;
701 
702   // Don't merge tiny functions using a thunk, since it can just end up
703   // making the function larger.
704   if (F->size() == 1) {
705     if (F->front().sizeWithoutDebug() < 2) {
706       LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
707                         << " is too small to bother creating a thunk for\n");
708       return false;
709     }
710   }
711   return true;
712 }
713 
714 /// Copy all metadata of a specific kind from one function to another.
715 static void copyMetadataIfPresent(Function *From, Function *To,
716                                   StringRef Kind) {
717   SmallVector<MDNode *, 4> MDs;
718   From->getMetadata(Kind, MDs);
719   for (MDNode *MD : MDs)
720     To->addMetadata(Kind, *MD);
721 }
722 
723 // Replace G with a simple tail call to bitcast(F). Also (unless
724 // MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
725 // delete G. Under MergeFunctionsPDI, we use G itself for creating
726 // the thunk as we preserve the debug info (and associated instructions)
727 // from G's entry block pertaining to G's incoming arguments which are
728 // passed on as corresponding arguments in the call that G makes to F.
729 // For better debugability, under MergeFunctionsPDI, we do not modify G's
730 // call sites to point to F even when within the same translation unit.
731 void MergeFunctions::writeThunk(Function *F, Function *G) {
732   BasicBlock *GEntryBlock = nullptr;
733   std::vector<Instruction *> PDIUnrelatedWL;
734   std::vector<DbgVariableRecord *> PDVRUnrelatedWL;
735   BasicBlock *BB = nullptr;
736   Function *NewG = nullptr;
737   if (MergeFunctionsPDI) {
738     LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
739                          "function as thunk; retain original: "
740                       << G->getName() << "()\n");
741     GEntryBlock = &G->getEntryBlock();
742     LLVM_DEBUG(
743         dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
744                   "debug info for "
745                << G->getName() << "() {\n");
746     filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL, PDVRUnrelatedWL);
747     GEntryBlock->getTerminator()->eraseFromParent();
748     BB = GEntryBlock;
749   } else {
750     NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
751                             G->getAddressSpace(), "", G->getParent());
752     NewG->setComdat(G->getComdat());
753     NewG->IsNewDbgInfoFormat = G->IsNewDbgInfoFormat;
754     BB = BasicBlock::Create(F->getContext(), "", NewG);
755   }
756 
757   IRBuilder<> Builder(BB);
758   Function *H = MergeFunctionsPDI ? G : NewG;
759   SmallVector<Value *, 16> Args;
760   unsigned i = 0;
761   FunctionType *FFTy = F->getFunctionType();
762   for (Argument &AI : H->args()) {
763     Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
764     ++i;
765   }
766 
767   CallInst *CI = Builder.CreateCall(F, Args);
768   ReturnInst *RI = nullptr;
769   bool isSwiftTailCall = F->getCallingConv() == CallingConv::SwiftTail &&
770                          G->getCallingConv() == CallingConv::SwiftTail;
771   CI->setTailCallKind(isSwiftTailCall ? llvm::CallInst::TCK_MustTail
772                                       : llvm::CallInst::TCK_Tail);
773   CI->setCallingConv(F->getCallingConv());
774   CI->setAttributes(F->getAttributes());
775   if (H->getReturnType()->isVoidTy()) {
776     RI = Builder.CreateRetVoid();
777   } else {
778     RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
779   }
780 
781   if (MergeFunctionsPDI) {
782     DISubprogram *DIS = G->getSubprogram();
783     if (DIS) {
784       DebugLoc CIDbgLoc =
785           DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
786       DebugLoc RIDbgLoc =
787           DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
788       CI->setDebugLoc(CIDbgLoc);
789       RI->setDebugLoc(RIDbgLoc);
790     } else {
791       LLVM_DEBUG(
792           dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
793                  << G->getName() << "()\n");
794     }
795     eraseTail(G);
796     eraseInstsUnrelatedToPDI(PDIUnrelatedWL, PDVRUnrelatedWL);
797     LLVM_DEBUG(
798         dbgs() << "} // End of parameter related debug info filtering for: "
799                << G->getName() << "()\n");
800   } else {
801     NewG->copyAttributesFrom(G);
802     NewG->takeName(G);
803     // Ensure CFI type metadata is propagated to the new function.
804     copyMetadataIfPresent(G, NewG, "type");
805     copyMetadataIfPresent(G, NewG, "kcfi_type");
806     removeUsers(G);
807     G->replaceAllUsesWith(NewG);
808     G->eraseFromParent();
809   }
810 
811   LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
812   ++NumThunksWritten;
813 }
814 
815 // Whether this function may be replaced by an alias
816 static bool canCreateAliasFor(Function *F) {
817   if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
818     return false;
819 
820   // We should only see linkages supported by aliases here
821   assert(F->hasLocalLinkage() || F->hasExternalLinkage()
822       || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
823   return true;
824 }
825 
826 // Replace G with an alias to F (deleting function G)
827 void MergeFunctions::writeAlias(Function *F, Function *G) {
828   PointerType *PtrType = G->getType();
829   auto *GA = GlobalAlias::create(G->getValueType(), PtrType->getAddressSpace(),
830                                  G->getLinkage(), "", F, G->getParent());
831 
832   const MaybeAlign FAlign = F->getAlign();
833   const MaybeAlign GAlign = G->getAlign();
834   if (FAlign || GAlign)
835     F->setAlignment(std::max(FAlign.valueOrOne(), GAlign.valueOrOne()));
836   else
837     F->setAlignment(std::nullopt);
838   GA->takeName(G);
839   GA->setVisibility(G->getVisibility());
840   GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
841 
842   removeUsers(G);
843   G->replaceAllUsesWith(GA);
844   G->eraseFromParent();
845 
846   LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
847   ++NumAliasesWritten;
848 }
849 
850 // Replace G with an alias to F if possible, or a thunk to F if
851 // profitable. Returns false if neither is the case.
852 bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
853   if (canCreateAliasFor(G)) {
854     writeAlias(F, G);
855     return true;
856   }
857   if (canCreateThunkFor(F)) {
858     writeThunk(F, G);
859     return true;
860   }
861   return false;
862 }
863 
864 // Merge two equivalent functions. Upon completion, Function G is deleted.
865 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
866   if (F->isInterposable()) {
867     assert(G->isInterposable());
868 
869     // Both writeThunkOrAlias() calls below must succeed, either because we can
870     // create aliases for G and NewF, or because a thunk for F is profitable.
871     // F here has the same signature as NewF below, so that's what we check.
872     if (!canCreateThunkFor(F) &&
873         (!canCreateAliasFor(F) || !canCreateAliasFor(G)))
874       return;
875 
876     // Make them both thunks to the same internal function.
877     Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
878                                       F->getAddressSpace(), "", F->getParent());
879     NewF->copyAttributesFrom(F);
880     NewF->takeName(F);
881     NewF->IsNewDbgInfoFormat = F->IsNewDbgInfoFormat;
882     // Ensure CFI type metadata is propagated to the new function.
883     copyMetadataIfPresent(F, NewF, "type");
884     copyMetadataIfPresent(F, NewF, "kcfi_type");
885     removeUsers(F);
886     F->replaceAllUsesWith(NewF);
887 
888     // We collect alignment before writeThunkOrAlias that overwrites NewF and
889     // G's content.
890     const MaybeAlign NewFAlign = NewF->getAlign();
891     const MaybeAlign GAlign = G->getAlign();
892 
893     writeThunkOrAlias(F, G);
894     writeThunkOrAlias(F, NewF);
895 
896     if (NewFAlign || GAlign)
897       F->setAlignment(std::max(NewFAlign.valueOrOne(), GAlign.valueOrOne()));
898     else
899       F->setAlignment(std::nullopt);
900     F->setLinkage(GlobalValue::PrivateLinkage);
901     ++NumDoubleWeak;
902     ++NumFunctionsMerged;
903   } else {
904     // For better debugability, under MergeFunctionsPDI, we do not modify G's
905     // call sites to point to F even when within the same translation unit.
906     if (!G->isInterposable() && !MergeFunctionsPDI) {
907       // Functions referred to by llvm.used/llvm.compiler.used are special:
908       // there are uses of the symbol name that are not visible to LLVM,
909       // usually from inline asm.
910       if (G->hasGlobalUnnamedAddr() && !Used.contains(G)) {
911         // G might have been a key in our GlobalNumberState, and it's illegal
912         // to replace a key in ValueMap<GlobalValue *> with a non-global.
913         GlobalNumbers.erase(G);
914         // If G's address is not significant, replace it entirely.
915         removeUsers(G);
916         G->replaceAllUsesWith(F);
917       } else {
918         // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
919         // above).
920         replaceDirectCallers(G, F);
921       }
922     }
923 
924     // If G was internal then we may have replaced all uses of G with F. If so,
925     // stop here and delete G. There's no need for a thunk. (See note on
926     // MergeFunctionsPDI above).
927     if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
928       G->eraseFromParent();
929       ++NumFunctionsMerged;
930       return;
931     }
932 
933     if (writeThunkOrAlias(F, G)) {
934       ++NumFunctionsMerged;
935     }
936   }
937 }
938 
939 /// Replace function F by function G.
940 void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
941                                            Function *G) {
942   Function *F = FN.getFunc();
943   assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
944          "The two functions must be equal");
945 
946   auto I = FNodesInTree.find(F);
947   assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
948   assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
949 
950   FnTreeType::iterator IterToFNInFnTree = I->second;
951   assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
952   // Remove F -> FN and insert G -> FN
953   FNodesInTree.erase(I);
954   FNodesInTree.insert({G, IterToFNInFnTree});
955   // Replace F with G in FN, which is stored inside the FnTree.
956   FN.replaceBy(G);
957 }
958 
959 // Ordering for functions that are equal under FunctionComparator
960 static bool isFuncOrderCorrect(const Function *F, const Function *G) {
961   if (F->isInterposable() != G->isInterposable()) {
962     // Strong before weak, because the weak function may call the strong
963     // one, but not the other way around.
964     return !F->isInterposable();
965   }
966   if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
967     // External before local, because we definitely have to keep the external
968     // function, but may be able to drop the local one.
969     return !F->hasLocalLinkage();
970   }
971   // Impose a total order (by name) on the replacement of functions. This is
972   // important when operating on more than one module independently to prevent
973   // cycles of thunks calling each other when the modules are linked together.
974   return F->getName() <= G->getName();
975 }
976 
977 // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
978 // that was already inserted.
979 bool MergeFunctions::insert(Function *NewFunction) {
980   std::pair<FnTreeType::iterator, bool> Result =
981       FnTree.insert(FunctionNode(NewFunction));
982 
983   if (Result.second) {
984     assert(FNodesInTree.count(NewFunction) == 0);
985     FNodesInTree.insert({NewFunction, Result.first});
986     LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
987                       << '\n');
988     return false;
989   }
990 
991   const FunctionNode &OldF = *Result.first;
992 
993   if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
994     // Swap the two functions.
995     Function *F = OldF.getFunc();
996     replaceFunctionInTree(*Result.first, NewFunction);
997     NewFunction = F;
998     assert(OldF.getFunc() != F && "Must have swapped the functions.");
999   }
1000 
1001   LLVM_DEBUG(dbgs() << "  " << OldF.getFunc()->getName()
1002                     << " == " << NewFunction->getName() << '\n');
1003 
1004   Function *DeleteF = NewFunction;
1005   mergeTwoFunctions(OldF.getFunc(), DeleteF);
1006   return true;
1007 }
1008 
1009 // Remove a function from FnTree. If it was already in FnTree, add
1010 // it to Deferred so that we'll look at it in the next round.
1011 void MergeFunctions::remove(Function *F) {
1012   auto I = FNodesInTree.find(F);
1013   if (I != FNodesInTree.end()) {
1014     LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
1015     FnTree.erase(I->second);
1016     // I->second has been invalidated, remove it from the FNodesInTree map to
1017     // preserve the invariant.
1018     FNodesInTree.erase(I);
1019     Deferred.emplace_back(F);
1020   }
1021 }
1022 
1023 // For each instruction used by the value, remove() the function that contains
1024 // the instruction. This should happen right before a call to RAUW.
1025 void MergeFunctions::removeUsers(Value *V) {
1026   for (User *U : V->users())
1027     if (auto *I = dyn_cast<Instruction>(U))
1028       remove(I->getFunction());
1029 }
1030