xref: /src/contrib/llvm-project/llvm/lib/Transforms/IPO/MergeFunctions.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1009b1c42SEd Schouten //===- MergeFunctions.cpp - Merge identical functions ---------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This pass looks for equivalent functions that are mergable and folds them.
10009b1c42SEd Schouten //
115ca98fd9SDimitry Andric // Order relation is defined on set of functions. It was made through
125ca98fd9SDimitry Andric // special function comparison procedure that returns
135ca98fd9SDimitry Andric // 0 when functions are equal,
145ca98fd9SDimitry Andric // -1 when Left function is less than right function, and
155ca98fd9SDimitry Andric // 1 for opposite case. We need total-ordering, so we need to maintain
165ca98fd9SDimitry Andric // four properties on the functions set:
175ca98fd9SDimitry Andric // a <= a (reflexivity)
185ca98fd9SDimitry Andric // if a <= b and b <= a then a = b (antisymmetry)
195ca98fd9SDimitry Andric // if a <= b and b <= c then a <= c (transitivity).
205ca98fd9SDimitry Andric // for all a and b: a <= b or b <= a (totality).
21009b1c42SEd Schouten //
225ca98fd9SDimitry Andric // Comparison iterates through each instruction in each basic block.
235ca98fd9SDimitry Andric // Functions are kept on binary tree. For each new function F we perform
245ca98fd9SDimitry Andric // lookup in binary tree.
255ca98fd9SDimitry Andric // In practice it works the following way:
265ca98fd9SDimitry Andric // -- We define Function* container class with custom "operator<" (FunctionPtr).
275ca98fd9SDimitry Andric // -- "FunctionPtr" instances are stored in std::set collection, so every
285ca98fd9SDimitry Andric //    std::set::insert operation will give you result in log(N) time.
29009b1c42SEd Schouten //
30dd58ef01SDimitry Andric // As an optimization, a hash of the function structure is calculated first, and
31dd58ef01SDimitry Andric // two functions are only compared if they have the same hash. This hash is
32dd58ef01SDimitry Andric // cheap to compute, and has the property that if function F == G according to
33dd58ef01SDimitry Andric // the comparison function, then hash(F) == hash(G). This consistency property
34dd58ef01SDimitry Andric // is critical to ensuring all possible merging opportunities are exploited.
35dd58ef01SDimitry Andric // Collisions in the hash affect the speed of the pass but not the correctness
36dd58ef01SDimitry Andric // or determinism of the resulting transformation.
37dd58ef01SDimitry Andric //
38abdf259dSRoman Divacky // When a match is found the functions are folded. If both functions are
39abdf259dSRoman Divacky // overridable, we move the functionality into a new internal function and
40abdf259dSRoman Divacky // leave two overridable thunks to it.
41009b1c42SEd Schouten //
42009b1c42SEd Schouten //===----------------------------------------------------------------------===//
43009b1c42SEd Schouten //
44009b1c42SEd Schouten // Future work:
45009b1c42SEd Schouten //
46009b1c42SEd Schouten // * virtual functions.
47009b1c42SEd Schouten //
48009b1c42SEd Schouten // Many functions have their address taken by the virtual function table for
49009b1c42SEd Schouten // the object they belong to. However, as long as it's only used for a lookup
50d39c594dSDimitry Andric // and call, this is irrelevant, and we'd like to fold such functions.
51009b1c42SEd Schouten //
52d39c594dSDimitry Andric // * be smarter about bitcasts.
53abdf259dSRoman Divacky //
54abdf259dSRoman Divacky // In order to fold functions, we will sometimes add either bitcast instructions
55abdf259dSRoman Divacky // or bitcast constant expressions. Unfortunately, this can confound further
56abdf259dSRoman Divacky // analysis since the two functions differ where one has a bitcast and the
57d39c594dSDimitry Andric // other doesn't. We should learn to look through bitcasts.
58abdf259dSRoman Divacky //
595ca98fd9SDimitry Andric // * Compare complex types with pointer types inside.
605ca98fd9SDimitry Andric // * Compare cross-reference cases.
615ca98fd9SDimitry Andric // * Compare complex expressions.
625ca98fd9SDimitry Andric //
635ca98fd9SDimitry Andric // All the three issues above could be described as ability to prove that
645ca98fd9SDimitry Andric // fA == fB == fC == fE == fF == fG in example below:
655ca98fd9SDimitry Andric //
665ca98fd9SDimitry Andric //  void fA() {
675ca98fd9SDimitry Andric //    fB();
685ca98fd9SDimitry Andric //  }
695ca98fd9SDimitry Andric //  void fB() {
705ca98fd9SDimitry Andric //    fA();
715ca98fd9SDimitry Andric //  }
725ca98fd9SDimitry Andric //
735ca98fd9SDimitry Andric //  void fE() {
745ca98fd9SDimitry Andric //    fF();
755ca98fd9SDimitry Andric //  }
765ca98fd9SDimitry Andric //  void fF() {
775ca98fd9SDimitry Andric //    fG();
785ca98fd9SDimitry Andric //  }
795ca98fd9SDimitry Andric //  void fG() {
805ca98fd9SDimitry Andric //    fE();
815ca98fd9SDimitry Andric //  }
825ca98fd9SDimitry Andric //
835ca98fd9SDimitry Andric // Simplest cross-reference case (fA <--> fB) was implemented in previous
845ca98fd9SDimitry Andric // versions of MergeFunctions, though it presented only in two function pairs
855ca98fd9SDimitry Andric // in test-suite (that counts >50k functions)
865ca98fd9SDimitry Andric // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
875ca98fd9SDimitry Andric // could cover much more cases.
885ca98fd9SDimitry Andric //
89009b1c42SEd Schouten //===----------------------------------------------------------------------===//
90009b1c42SEd Schouten 
91145449b1SDimitry Andric #include "llvm/Transforms/IPO/MergeFunctions.h"
92044eb2f6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
93044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
9458b69754SDimitry Andric #include "llvm/ADT/Statistic.h"
95044eb2f6SDimitry Andric #include "llvm/IR/Argument.h"
96044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
97044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
984a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
99044eb2f6SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
100044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
101044eb2f6SDimitry Andric #include "llvm/IR/DerivedTypes.h"
102044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
103044eb2f6SDimitry Andric #include "llvm/IR/GlobalValue.h"
1044a16efa3SDimitry Andric #include "llvm/IR/IRBuilder.h"
105044eb2f6SDimitry Andric #include "llvm/IR/InstrTypes.h"
106044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
1074a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
10871d5a254SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
1094a16efa3SDimitry Andric #include "llvm/IR/Module.h"
110b1c73532SDimitry Andric #include "llvm/IR/StructuralHash.h"
111044eb2f6SDimitry Andric #include "llvm/IR/Type.h"
112044eb2f6SDimitry Andric #include "llvm/IR/Use.h"
113044eb2f6SDimitry Andric #include "llvm/IR/User.h"
114044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
1155ca98fd9SDimitry Andric #include "llvm/IR/ValueHandle.h"
116044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
1175ca98fd9SDimitry Andric #include "llvm/Support/CommandLine.h"
118009b1c42SEd Schouten #include "llvm/Support/Debug.h"
11959850d08SRoman Divacky #include "llvm/Support/raw_ostream.h"
12001095a5dSDimitry Andric #include "llvm/Transforms/IPO.h"
121b915e9e0SDimitry Andric #include "llvm/Transforms/Utils/FunctionComparator.h"
122145449b1SDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
123044eb2f6SDimitry Andric #include <algorithm>
124044eb2f6SDimitry Andric #include <cassert>
125044eb2f6SDimitry Andric #include <iterator>
126044eb2f6SDimitry Andric #include <set>
127044eb2f6SDimitry Andric #include <utility>
128009b1c42SEd Schouten #include <vector>
129dd58ef01SDimitry Andric 
130009b1c42SEd Schouten using namespace llvm;
131009b1c42SEd Schouten 
1325ca98fd9SDimitry Andric #define DEBUG_TYPE "mergefunc"
1335ca98fd9SDimitry Andric 
134009b1c42SEd Schouten STATISTIC(NumFunctionsMerged, "Number of functions merged");
135cf099d11SDimitry Andric STATISTIC(NumThunksWritten, "Number of thunks generated");
136d8e91e46SDimitry Andric STATISTIC(NumAliasesWritten, "Number of aliases generated");
137cf099d11SDimitry Andric STATISTIC(NumDoubleWeak, "Number of new functions created");
138cf099d11SDimitry Andric 
139145449b1SDimitry Andric static cl::opt<unsigned> NumFunctionsForVerificationCheck(
140145449b1SDimitry Andric     "mergefunc-verify",
141145449b1SDimitry Andric     cl::desc("How many functions in a module could be used for "
142145449b1SDimitry Andric              "MergeFunctions to pass a basic correctness check. "
1435ca98fd9SDimitry Andric              "'0' disables this check. Works only with '-debug' key."),
1445ca98fd9SDimitry Andric     cl::init(0), cl::Hidden);
145009b1c42SEd Schouten 
14671d5a254SDimitry Andric // Under option -mergefunc-preserve-debug-info we:
14771d5a254SDimitry Andric // - Do not create a new function for a thunk.
14871d5a254SDimitry Andric // - Retain the debug info for a thunk's parameters (and associated
14971d5a254SDimitry Andric //   instructions for the debug info) from the entry block.
15071d5a254SDimitry Andric //   Note: -debug will display the algorithm at work.
15171d5a254SDimitry Andric // - Create debug-info for the call (to the shared implementation) made by
15271d5a254SDimitry Andric //   a thunk and its return value.
15371d5a254SDimitry Andric // - Erase the rest of the function, retaining the (minimally sized) entry
15471d5a254SDimitry Andric //   block to create a thunk.
15571d5a254SDimitry Andric // - Preserve a thunk's call site to point to the thunk even when both occur
15671d5a254SDimitry Andric //   within the same translation unit, to aid debugability. Note that this
15771d5a254SDimitry Andric //   behaviour differs from the underlying -mergefunc implementation which
15871d5a254SDimitry Andric //   modifies the thunk's call site to point to the shared implementation
15971d5a254SDimitry Andric //   when both occur within the same translation unit.
16071d5a254SDimitry Andric static cl::opt<bool>
16171d5a254SDimitry Andric     MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
16271d5a254SDimitry Andric                       cl::init(false),
16371d5a254SDimitry Andric                       cl::desc("Preserve debug info in thunk when mergefunc "
16471d5a254SDimitry Andric                                "transformations are made."));
16571d5a254SDimitry Andric 
166d8e91e46SDimitry Andric static cl::opt<bool>
167d8e91e46SDimitry Andric     MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
168d8e91e46SDimitry Andric                           cl::init(false),
169d8e91e46SDimitry Andric                           cl::desc("Allow mergefunc to create aliases"));
170d8e91e46SDimitry Andric 
171d39c594dSDimitry Andric namespace {
172cf099d11SDimitry Andric 
17367c32a98SDimitry Andric class FunctionNode {
17485d8b2bbSDimitry Andric   mutable AssertingVH<Function> F;
175b1c73532SDimitry Andric   IRHash Hash;
176044eb2f6SDimitry Andric 
1775ca98fd9SDimitry Andric public:
178dd58ef01SDimitry Andric   // Note the hash is recalculated potentially multiple times, but it is cheap.
FunctionNode(Function * F)179b1c73532SDimitry Andric   FunctionNode(Function *F) : F(F), Hash(StructuralHash(*F)) {}
180044eb2f6SDimitry Andric 
getFunc() const1815ca98fd9SDimitry Andric   Function *getFunc() const { return F; }
getHash() const182b1c73532SDimitry Andric   IRHash getHash() const { return Hash; }
18385d8b2bbSDimitry Andric 
18485d8b2bbSDimitry Andric   /// Replace the reference to the function F by the function G, assuming their
18585d8b2bbSDimitry Andric   /// implementations are equal.
replaceBy(Function * G) const18685d8b2bbSDimitry Andric   void replaceBy(Function *G) const {
18785d8b2bbSDimitry Andric     F = G;
18885d8b2bbSDimitry Andric   }
1895ca98fd9SDimitry Andric };
190cf099d11SDimitry Andric 
191cf099d11SDimitry Andric /// MergeFunctions finds functions which will generate identical machine code,
192cf099d11SDimitry Andric /// by considering all pointer types to be equivalent. Once identified,
193cf099d11SDimitry Andric /// MergeFunctions will fold them by replacing a call to one to a call to a
194cf099d11SDimitry Andric /// bitcast of the other.
195706b4fc4SDimitry Andric class MergeFunctions {
196cf099d11SDimitry Andric public:
MergeFunctions()197706b4fc4SDimitry Andric   MergeFunctions() : FnTree(FunctionNodeCmp(&GlobalNumbers)) {
198cf099d11SDimitry Andric   }
199cf099d11SDimitry Andric 
200706b4fc4SDimitry Andric   bool runOnModule(Module &M);
201cf099d11SDimitry Andric 
202cf099d11SDimitry Andric private:
203dd58ef01SDimitry Andric   // The function comparison operator is provided here so that FunctionNodes do
204dd58ef01SDimitry Andric   // not need to become larger with another pointer.
205dd58ef01SDimitry Andric   class FunctionNodeCmp {
206dd58ef01SDimitry Andric     GlobalNumberState* GlobalNumbers;
207044eb2f6SDimitry Andric 
208dd58ef01SDimitry Andric   public:
FunctionNodeCmp(GlobalNumberState * GN)209dd58ef01SDimitry Andric     FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
210044eb2f6SDimitry Andric 
operator ()(const FunctionNode & LHS,const FunctionNode & RHS) const211dd58ef01SDimitry Andric     bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
212dd58ef01SDimitry Andric       // Order first by hashes, then full function comparison.
213dd58ef01SDimitry Andric       if (LHS.getHash() != RHS.getHash())
214dd58ef01SDimitry Andric         return LHS.getHash() < RHS.getHash();
215dd58ef01SDimitry Andric       FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
216e3b55780SDimitry Andric       return FCmp.compare() < 0;
217dd58ef01SDimitry Andric     }
218dd58ef01SDimitry Andric   };
219044eb2f6SDimitry Andric   using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
220dd58ef01SDimitry Andric 
221dd58ef01SDimitry Andric   GlobalNumberState GlobalNumbers;
222cf099d11SDimitry Andric 
223cf099d11SDimitry Andric   /// A work queue of functions that may have been modified and should be
224cf099d11SDimitry Andric   /// analyzed again.
225a303c417SDimitry Andric   std::vector<WeakTrackingVH> Deferred;
226cf099d11SDimitry Andric 
227145449b1SDimitry Andric   /// Set of values marked as used in llvm.used and llvm.compiler.used.
228145449b1SDimitry Andric   SmallPtrSet<GlobalValue *, 4> Used;
229145449b1SDimitry Andric 
230044eb2f6SDimitry Andric #ifndef NDEBUG
2315ca98fd9SDimitry Andric   /// Checks the rules of order relation introduced among functions set.
232145449b1SDimitry Andric   /// Returns true, if check has been passed, and false if failed.
233145449b1SDimitry Andric   bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
234a303c417SDimitry Andric #endif
235cf099d11SDimitry Andric 
2365ca98fd9SDimitry Andric   /// Insert a ComparableFunction into the FnTree, or merge it away if it's
2375ca98fd9SDimitry Andric   /// equal to one that's already present.
2385ca98fd9SDimitry Andric   bool insert(Function *NewFunction);
2395ca98fd9SDimitry Andric 
2405ca98fd9SDimitry Andric   /// Remove a Function from the FnTree and queue it up for a second sweep of
241cf099d11SDimitry Andric   /// analysis.
242cf099d11SDimitry Andric   void remove(Function *F);
243cf099d11SDimitry Andric 
2445ca98fd9SDimitry Andric   /// Find the functions that use this Value and remove them from FnTree and
245cf099d11SDimitry Andric   /// queue the functions.
246cf099d11SDimitry Andric   void removeUsers(Value *V);
247cf099d11SDimitry Andric 
248cf099d11SDimitry Andric   /// Replace all direct calls of Old with calls of New. Will bitcast New if
249cf099d11SDimitry Andric   /// necessary to make types match.
250cf099d11SDimitry Andric   void replaceDirectCallers(Function *Old, Function *New);
251cf099d11SDimitry Andric 
252cf099d11SDimitry Andric   /// Merge two equivalent functions. Upon completion, G may be deleted, or may
253cf099d11SDimitry Andric   /// be converted into a thunk. In either case, it should never be visited
254cf099d11SDimitry Andric   /// again.
255cf099d11SDimitry Andric   void mergeTwoFunctions(Function *F, Function *G);
256cf099d11SDimitry Andric 
25771d5a254SDimitry Andric   /// Fill PDIUnrelatedWL with instructions from the entry block that are
25871d5a254SDimitry Andric   /// unrelated to parameter related debug info.
259ac9a064cSDimitry Andric   /// \param PDVRUnrelatedWL The equivalent non-intrinsic debug records.
260ac9a064cSDimitry Andric   void
261ac9a064cSDimitry Andric   filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
262ac9a064cSDimitry Andric                             std::vector<Instruction *> &PDIUnrelatedWL,
263ac9a064cSDimitry Andric                             std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
26471d5a254SDimitry Andric 
26571d5a254SDimitry Andric   /// Erase the rest of the CFG (i.e. barring the entry block).
26671d5a254SDimitry Andric   void eraseTail(Function *G);
26771d5a254SDimitry Andric 
26871d5a254SDimitry Andric   /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
26971d5a254SDimitry Andric   /// parameter debug info, from the entry block.
270ac9a064cSDimitry Andric   /// \param PDVRUnrelatedWL contains the equivalent set of non-instruction
271ac9a064cSDimitry Andric   /// debug-info records.
272ac9a064cSDimitry Andric   void
273ac9a064cSDimitry Andric   eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL,
274ac9a064cSDimitry Andric                            std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
27571d5a254SDimitry Andric 
27671d5a254SDimitry Andric   /// Replace G with a simple tail call to bitcast(F). Also (unless
27771d5a254SDimitry Andric   /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
27871d5a254SDimitry Andric   /// delete G.
279cf099d11SDimitry Andric   void writeThunk(Function *F, Function *G);
280cf099d11SDimitry Andric 
281d8e91e46SDimitry Andric   // Replace G with an alias to F (deleting function G)
282d8e91e46SDimitry Andric   void writeAlias(Function *F, Function *G);
283d8e91e46SDimitry Andric 
284e6d15924SDimitry Andric   // Replace G with an alias to F if possible, or a thunk to F if possible.
285e6d15924SDimitry Andric   // Returns false if neither is the case.
286d8e91e46SDimitry Andric   bool writeThunkOrAlias(Function *F, Function *G);
287d8e91e46SDimitry Andric 
28885d8b2bbSDimitry Andric   /// Replace function F with function G in the function tree.
289dd58ef01SDimitry Andric   void replaceFunctionInTree(const FunctionNode &FN, Function *G);
29085d8b2bbSDimitry Andric 
291cf099d11SDimitry Andric   /// The set of all distinct functions. Use the insert() and remove() methods
292dd58ef01SDimitry Andric   /// to modify it. The map allows efficient lookup and deferring of Functions.
2935ca98fd9SDimitry Andric   FnTreeType FnTree;
294044eb2f6SDimitry Andric 
295dd58ef01SDimitry Andric   // Map functions to the iterators of the FunctionNode which contains them
296dd58ef01SDimitry Andric   // in the FnTree. This must be updated carefully whenever the FnTree is
297dd58ef01SDimitry Andric   // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
298dd58ef01SDimitry Andric   // dangling iterators into FnTree. The invariant that preserves this is that
299dd58ef01SDimitry Andric   // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
300d8e91e46SDimitry Andric   DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
301cf099d11SDimitry Andric };
302cf099d11SDimitry Andric } // end anonymous namespace
303cf099d11SDimitry Andric 
run(Module & M,ModuleAnalysisManager & AM)304706b4fc4SDimitry Andric PreservedAnalyses MergeFunctionsPass::run(Module &M,
305706b4fc4SDimitry Andric                                           ModuleAnalysisManager &AM) {
306706b4fc4SDimitry Andric   MergeFunctions MF;
307706b4fc4SDimitry Andric   if (!MF.runOnModule(M))
308706b4fc4SDimitry Andric     return PreservedAnalyses::all();
309706b4fc4SDimitry Andric   return PreservedAnalyses::none();
310cf099d11SDimitry Andric }
311cf099d11SDimitry Andric 
312a303c417SDimitry Andric #ifndef NDEBUG
doFunctionalCheck(std::vector<WeakTrackingVH> & Worklist)313145449b1SDimitry Andric bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
314145449b1SDimitry Andric   if (const unsigned Max = NumFunctionsForVerificationCheck) {
3155ca98fd9SDimitry Andric     unsigned TripleNumber = 0;
3165ca98fd9SDimitry Andric     bool Valid = true;
3175ca98fd9SDimitry Andric 
318145449b1SDimitry Andric     dbgs() << "MERGEFUNC-VERIFY: Started for first " << Max << " functions.\n";
3195ca98fd9SDimitry Andric 
3205ca98fd9SDimitry Andric     unsigned i = 0;
321a303c417SDimitry Andric     for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
322a303c417SDimitry Andric                                                E = Worklist.end();
3235ca98fd9SDimitry Andric          I != E && i < Max; ++I, ++i) {
3245ca98fd9SDimitry Andric       unsigned j = i;
325a303c417SDimitry Andric       for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
326a303c417SDimitry Andric            ++J, ++j) {
3275ca98fd9SDimitry Andric         Function *F1 = cast<Function>(*I);
3285ca98fd9SDimitry Andric         Function *F2 = cast<Function>(*J);
329dd58ef01SDimitry Andric         int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
330dd58ef01SDimitry Andric         int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
3315ca98fd9SDimitry Andric 
3325ca98fd9SDimitry Andric         // If F1 <= F2, then F2 >= F1, otherwise report failure.
3335ca98fd9SDimitry Andric         if (Res1 != -Res2) {
334145449b1SDimitry Andric           dbgs() << "MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
3355ca98fd9SDimitry Andric                  << "\n";
33671d5a254SDimitry Andric           dbgs() << *F1 << '\n' << *F2 << '\n';
3375ca98fd9SDimitry Andric           Valid = false;
3385ca98fd9SDimitry Andric         }
3395ca98fd9SDimitry Andric 
3405ca98fd9SDimitry Andric         if (Res1 == 0)
3415ca98fd9SDimitry Andric           continue;
3425ca98fd9SDimitry Andric 
3435ca98fd9SDimitry Andric         unsigned k = j;
344a303c417SDimitry Andric         for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
3455ca98fd9SDimitry Andric              ++k, ++K, ++TripleNumber) {
3465ca98fd9SDimitry Andric           if (K == J)
3475ca98fd9SDimitry Andric             continue;
3485ca98fd9SDimitry Andric 
3495ca98fd9SDimitry Andric           Function *F3 = cast<Function>(*K);
350dd58ef01SDimitry Andric           int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
351dd58ef01SDimitry Andric           int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
3525ca98fd9SDimitry Andric 
3535ca98fd9SDimitry Andric           bool Transitive = true;
3545ca98fd9SDimitry Andric 
3555ca98fd9SDimitry Andric           if (Res1 != 0 && Res1 == Res4) {
3565ca98fd9SDimitry Andric             // F1 > F2, F2 > F3 => F1 > F3
3575ca98fd9SDimitry Andric             Transitive = Res3 == Res1;
3585ca98fd9SDimitry Andric           } else if (Res3 != 0 && Res3 == -Res4) {
3595ca98fd9SDimitry Andric             // F1 > F3, F3 > F2 => F1 > F2
3605ca98fd9SDimitry Andric             Transitive = Res3 == Res1;
3615ca98fd9SDimitry Andric           } else if (Res4 != 0 && -Res3 == Res4) {
3625ca98fd9SDimitry Andric             // F2 > F3, F3 > F1 => F2 > F1
3635ca98fd9SDimitry Andric             Transitive = Res4 == -Res1;
3645ca98fd9SDimitry Andric           }
3655ca98fd9SDimitry Andric 
3665ca98fd9SDimitry Andric           if (!Transitive) {
367145449b1SDimitry Andric             dbgs() << "MERGEFUNC-VERIFY: Non-transitive; triple: "
3685ca98fd9SDimitry Andric                    << TripleNumber << "\n";
3695ca98fd9SDimitry Andric             dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
3705ca98fd9SDimitry Andric                    << Res4 << "\n";
37171d5a254SDimitry Andric             dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
3725ca98fd9SDimitry Andric             Valid = false;
3735ca98fd9SDimitry Andric           }
3745ca98fd9SDimitry Andric         }
3755ca98fd9SDimitry Andric       }
3765ca98fd9SDimitry Andric     }
3775ca98fd9SDimitry Andric 
378145449b1SDimitry Andric     dbgs() << "MERGEFUNC-VERIFY: " << (Valid ? "Passed." : "Failed.") << "\n";
3795ca98fd9SDimitry Andric     return Valid;
3805ca98fd9SDimitry Andric   }
3815ca98fd9SDimitry Andric   return true;
3825ca98fd9SDimitry Andric }
383a303c417SDimitry Andric #endif
3845ca98fd9SDimitry Andric 
385b1c73532SDimitry Andric /// Check whether \p F has an intrinsic which references
386b1c73532SDimitry Andric /// distinct metadata as an operand. The most common
387b1c73532SDimitry Andric /// instance of this would be CFI checks for function-local types.
hasDistinctMetadataIntrinsic(const Function & F)388b1c73532SDimitry Andric static bool hasDistinctMetadataIntrinsic(const Function &F) {
389b1c73532SDimitry Andric   for (const BasicBlock &BB : F) {
390b1c73532SDimitry Andric     for (const Instruction &I : BB.instructionsWithoutDebug()) {
391b1c73532SDimitry Andric       if (!isa<IntrinsicInst>(&I))
392b1c73532SDimitry Andric         continue;
393b1c73532SDimitry Andric 
394b1c73532SDimitry Andric       for (Value *Op : I.operands()) {
395b1c73532SDimitry Andric         auto *MDL = dyn_cast<MetadataAsValue>(Op);
396b1c73532SDimitry Andric         if (!MDL)
397b1c73532SDimitry Andric           continue;
398b1c73532SDimitry Andric         if (MDNode *N = dyn_cast<MDNode>(MDL->getMetadata()))
399b1c73532SDimitry Andric           if (N->isDistinct())
400b1c73532SDimitry Andric             return true;
401b1c73532SDimitry Andric       }
402b1c73532SDimitry Andric     }
403b1c73532SDimitry Andric   }
404b1c73532SDimitry Andric   return false;
405b1c73532SDimitry Andric }
406b1c73532SDimitry Andric 
407e6d15924SDimitry Andric /// Check whether \p F is eligible for function merging.
isEligibleForMerging(Function & F)408e6d15924SDimitry Andric static bool isEligibleForMerging(Function &F) {
409b1c73532SDimitry Andric   return !F.isDeclaration() && !F.hasAvailableExternallyLinkage() &&
410b1c73532SDimitry Andric          !hasDistinctMetadataIntrinsic(F);
411e6d15924SDimitry Andric }
412e6d15924SDimitry Andric 
runOnModule(Module & M)413cf099d11SDimitry Andric bool MergeFunctions::runOnModule(Module &M) {
414cf099d11SDimitry Andric   bool Changed = false;
415cf099d11SDimitry Andric 
416145449b1SDimitry Andric   SmallVector<GlobalValue *, 4> UsedV;
417145449b1SDimitry Andric   collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/false);
418145449b1SDimitry Andric   collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/true);
419145449b1SDimitry Andric   Used.insert(UsedV.begin(), UsedV.end());
420145449b1SDimitry Andric 
421dd58ef01SDimitry Andric   // All functions in the module, ordered by hash. Functions with a unique
422dd58ef01SDimitry Andric   // hash value are easily eliminated.
423b1c73532SDimitry Andric   std::vector<std::pair<IRHash, Function *>> HashedFuncs;
424dd58ef01SDimitry Andric   for (Function &Func : M) {
425e6d15924SDimitry Andric     if (isEligibleForMerging(Func)) {
426b1c73532SDimitry Andric       HashedFuncs.push_back({StructuralHash(Func), &Func});
427dd58ef01SDimitry Andric     }
428dd58ef01SDimitry Andric   }
429dd58ef01SDimitry Andric 
430e6d15924SDimitry Andric   llvm::stable_sort(HashedFuncs, less_first());
431dd58ef01SDimitry Andric 
432dd58ef01SDimitry Andric   auto S = HashedFuncs.begin();
433dd58ef01SDimitry Andric   for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
434dd58ef01SDimitry Andric     // If the hash value matches the previous value or the next one, we must
435dd58ef01SDimitry Andric     // consider merging it. Otherwise it is dropped and never considered again.
436dd58ef01SDimitry Andric     if ((I != S && std::prev(I)->first == I->first) ||
437dd58ef01SDimitry Andric         (std::next(I) != IE && std::next(I)->first == I->first) ) {
438a303c417SDimitry Andric       Deferred.push_back(WeakTrackingVH(I->second));
439dd58ef01SDimitry Andric     }
440cf099d11SDimitry Andric   }
441cf099d11SDimitry Andric 
442cf099d11SDimitry Andric   do {
443a303c417SDimitry Andric     std::vector<WeakTrackingVH> Worklist;
444cf099d11SDimitry Andric     Deferred.swap(Worklist);
445cf099d11SDimitry Andric 
446145449b1SDimitry Andric     LLVM_DEBUG(doFunctionalCheck(Worklist));
4475ca98fd9SDimitry Andric 
448eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
449eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
450cf099d11SDimitry Andric 
45101095a5dSDimitry Andric     // Insert functions and merge them.
452a303c417SDimitry Andric     for (WeakTrackingVH &I : Worklist) {
45301095a5dSDimitry Andric       if (!I)
45401095a5dSDimitry Andric         continue;
45501095a5dSDimitry Andric       Function *F = cast<Function>(I);
45601095a5dSDimitry Andric       if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage()) {
4575ca98fd9SDimitry Andric         Changed |= insert(F);
458cf099d11SDimitry Andric       }
459cf099d11SDimitry Andric     }
460eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
461cf099d11SDimitry Andric   } while (!Deferred.empty());
462cf099d11SDimitry Andric 
4635ca98fd9SDimitry Andric   FnTree.clear();
464d8e91e46SDimitry Andric   FNodesInTree.clear();
465dd58ef01SDimitry Andric   GlobalNumbers.clear();
466145449b1SDimitry Andric   Used.clear();
467cf099d11SDimitry Andric 
468cf099d11SDimitry Andric   return Changed;
469cf099d11SDimitry Andric }
470cf099d11SDimitry Andric 
471cf099d11SDimitry Andric // Replace direct callers of Old with New.
replaceDirectCallers(Function * Old,Function * New)472cf099d11SDimitry Andric void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
473c0981da4SDimitry Andric   for (Use &U : llvm::make_early_inc_range(Old->uses())) {
474c0981da4SDimitry Andric     CallBase *CB = dyn_cast<CallBase>(U.getUser());
475c0981da4SDimitry Andric     if (CB && CB->isCallee(&U)) {
476706b4fc4SDimitry Andric       // Do not copy attributes from the called function to the call-site.
477706b4fc4SDimitry Andric       // Function comparison ensures that the attributes are the same up to
478706b4fc4SDimitry Andric       // type congruences in byval(), in which case we need to keep the byval
479706b4fc4SDimitry Andric       // type of the call-site, not the callee function.
480cfca06d7SDimitry Andric       remove(CB->getFunction());
481b1c73532SDimitry Andric       U.set(New);
482cf099d11SDimitry Andric     }
483abdf259dSRoman Divacky   }
484abdf259dSRoman Divacky }
485abdf259dSRoman Divacky 
486f8af5cf6SDimitry Andric // Helper for writeThunk,
487f8af5cf6SDimitry Andric // Selects proper bitcast operation,
4885ca98fd9SDimitry Andric // but a bit simpler then CastInst::getCastOpcode.
createCast(IRBuilder<> & Builder,Value * V,Type * DestTy)48901095a5dSDimitry Andric static Value *createCast(IRBuilder<> &Builder, Value *V, Type *DestTy) {
490f8af5cf6SDimitry Andric   Type *SrcTy = V->getType();
4915ca98fd9SDimitry Andric   if (SrcTy->isStructTy()) {
4925ca98fd9SDimitry Andric     assert(DestTy->isStructTy());
4935ca98fd9SDimitry Andric     assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements());
494145449b1SDimitry Andric     Value *Result = PoisonValue::get(DestTy);
4955ca98fd9SDimitry Andric     for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) {
496e3b55780SDimitry Andric       Value *Element =
497e3b55780SDimitry Andric           createCast(Builder, Builder.CreateExtractValue(V, ArrayRef(I)),
4985ca98fd9SDimitry Andric                      DestTy->getStructElementType(I));
4995ca98fd9SDimitry Andric 
500e3b55780SDimitry Andric       Result = Builder.CreateInsertValue(Result, Element, ArrayRef(I));
5015ca98fd9SDimitry Andric     }
5025ca98fd9SDimitry Andric     return Result;
5035ca98fd9SDimitry Andric   }
5045ca98fd9SDimitry Andric   assert(!DestTy->isStructTy());
505f8af5cf6SDimitry Andric   if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
506f8af5cf6SDimitry Andric     return Builder.CreateIntToPtr(V, DestTy);
507f8af5cf6SDimitry Andric   else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
508f8af5cf6SDimitry Andric     return Builder.CreatePtrToInt(V, DestTy);
509f8af5cf6SDimitry Andric   else
510f8af5cf6SDimitry Andric     return Builder.CreateBitCast(V, DestTy);
511f8af5cf6SDimitry Andric }
512f8af5cf6SDimitry Andric 
51371d5a254SDimitry Andric // Erase the instructions in PDIUnrelatedWL as they are unrelated to the
51471d5a254SDimitry Andric // parameter debug info, from the entry block.
eraseInstsUnrelatedToPDI(std::vector<Instruction * > & PDIUnrelatedWL,std::vector<DbgVariableRecord * > & PDVRUnrelatedWL)51571d5a254SDimitry Andric void MergeFunctions::eraseInstsUnrelatedToPDI(
516ac9a064cSDimitry Andric     std::vector<Instruction *> &PDIUnrelatedWL,
517ac9a064cSDimitry Andric     std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
518eb11fae6SDimitry Andric   LLVM_DEBUG(
519eb11fae6SDimitry Andric       dbgs() << " Erasing instructions (in reverse order of appearance in "
52071d5a254SDimitry Andric                 "entry block) unrelated to parameter debug info from entry "
52171d5a254SDimitry Andric                 "block: {\n");
52271d5a254SDimitry Andric   while (!PDIUnrelatedWL.empty()) {
52371d5a254SDimitry Andric     Instruction *I = PDIUnrelatedWL.back();
524eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "  Deleting Instruction: ");
525eb11fae6SDimitry Andric     LLVM_DEBUG(I->print(dbgs()));
526eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
52771d5a254SDimitry Andric     I->eraseFromParent();
52871d5a254SDimitry Andric     PDIUnrelatedWL.pop_back();
52971d5a254SDimitry Andric   }
530ac9a064cSDimitry Andric 
531ac9a064cSDimitry Andric   while (!PDVRUnrelatedWL.empty()) {
532ac9a064cSDimitry Andric     DbgVariableRecord *DVR = PDVRUnrelatedWL.back();
533ac9a064cSDimitry Andric     LLVM_DEBUG(dbgs() << "  Deleting DbgVariableRecord ");
534ac9a064cSDimitry Andric     LLVM_DEBUG(DVR->print(dbgs()));
535ac9a064cSDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
536ac9a064cSDimitry Andric     DVR->eraseFromParent();
537ac9a064cSDimitry Andric     PDVRUnrelatedWL.pop_back();
538ac9a064cSDimitry Andric   }
539ac9a064cSDimitry Andric 
540eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
54171d5a254SDimitry Andric                        "debug info from entry block. \n");
54271d5a254SDimitry Andric }
54371d5a254SDimitry Andric 
54471d5a254SDimitry Andric // Reduce G to its entry block.
eraseTail(Function * G)54571d5a254SDimitry Andric void MergeFunctions::eraseTail(Function *G) {
54671d5a254SDimitry Andric   std::vector<BasicBlock *> WorklistBB;
547344a3780SDimitry Andric   for (BasicBlock &BB : drop_begin(*G)) {
548344a3780SDimitry Andric     BB.dropAllReferences();
549344a3780SDimitry Andric     WorklistBB.push_back(&BB);
55071d5a254SDimitry Andric   }
55171d5a254SDimitry Andric   while (!WorklistBB.empty()) {
55271d5a254SDimitry Andric     BasicBlock *BB = WorklistBB.back();
55371d5a254SDimitry Andric     BB->eraseFromParent();
55471d5a254SDimitry Andric     WorklistBB.pop_back();
55571d5a254SDimitry Andric   }
55671d5a254SDimitry Andric }
55771d5a254SDimitry Andric 
55871d5a254SDimitry Andric // We are interested in the following instructions from the entry block as being
55971d5a254SDimitry Andric // related to parameter debug info:
56071d5a254SDimitry Andric // - @llvm.dbg.declare
56171d5a254SDimitry Andric // - stores from the incoming parameters to locations on the stack-frame
56271d5a254SDimitry Andric // - allocas that create these locations on the stack-frame
56371d5a254SDimitry Andric // - @llvm.dbg.value
56471d5a254SDimitry Andric // - the entry block's terminator
56571d5a254SDimitry Andric // The rest are unrelated to debug info for the parameters; fill up
56671d5a254SDimitry Andric // PDIUnrelatedWL with such instructions.
filterInstsUnrelatedToPDI(BasicBlock * GEntryBlock,std::vector<Instruction * > & PDIUnrelatedWL,std::vector<DbgVariableRecord * > & PDVRUnrelatedWL)56771d5a254SDimitry Andric void MergeFunctions::filterInstsUnrelatedToPDI(
568ac9a064cSDimitry Andric     BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL,
569ac9a064cSDimitry Andric     std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
57071d5a254SDimitry Andric   std::set<Instruction *> PDIRelated;
571ac9a064cSDimitry Andric   std::set<DbgVariableRecord *> PDVRRelated;
572ac9a064cSDimitry Andric 
573ac9a064cSDimitry Andric   // Work out whether a dbg.value intrinsic or an equivalent DbgVariableRecord
574ac9a064cSDimitry Andric   // is a parameter to be preserved.
575ac9a064cSDimitry Andric   auto ExamineDbgValue = [](auto *DbgVal, auto &Container) {
576eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << " Deciding: ");
577ac9a064cSDimitry Andric     LLVM_DEBUG(DbgVal->print(dbgs()));
578eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
579ac9a064cSDimitry Andric     DILocalVariable *DILocVar = DbgVal->getVariable();
58071d5a254SDimitry Andric     if (DILocVar->isParameter()) {
581eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "  Include (parameter): ");
582ac9a064cSDimitry Andric       LLVM_DEBUG(DbgVal->print(dbgs()));
583eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
584ac9a064cSDimitry Andric       Container.insert(DbgVal);
58571d5a254SDimitry Andric     } else {
586eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "  Delete (!parameter): ");
587ac9a064cSDimitry Andric       LLVM_DEBUG(DbgVal->print(dbgs()));
588eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
58971d5a254SDimitry Andric     }
590ac9a064cSDimitry Andric   };
591ac9a064cSDimitry Andric 
592ac9a064cSDimitry Andric   auto ExamineDbgDeclare = [&PDIRelated](auto *DbgDecl, auto &Container) {
593eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << " Deciding: ");
594ac9a064cSDimitry Andric     LLVM_DEBUG(DbgDecl->print(dbgs()));
595eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
596ac9a064cSDimitry Andric     DILocalVariable *DILocVar = DbgDecl->getVariable();
59771d5a254SDimitry Andric     if (DILocVar->isParameter()) {
598eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "  Parameter: ");
599eb11fae6SDimitry Andric       LLVM_DEBUG(DILocVar->print(dbgs()));
600ac9a064cSDimitry Andric       AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DbgDecl->getAddress());
60171d5a254SDimitry Andric       if (AI) {
602eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "  Processing alloca users: ");
603eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "\n");
60471d5a254SDimitry Andric         for (User *U : AI->users()) {
60571d5a254SDimitry Andric           if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
60671d5a254SDimitry Andric             if (Value *Arg = SI->getValueOperand()) {
607344a3780SDimitry Andric               if (isa<Argument>(Arg)) {
608eb11fae6SDimitry Andric                 LLVM_DEBUG(dbgs() << "  Include: ");
609eb11fae6SDimitry Andric                 LLVM_DEBUG(AI->print(dbgs()));
610eb11fae6SDimitry Andric                 LLVM_DEBUG(dbgs() << "\n");
61171d5a254SDimitry Andric                 PDIRelated.insert(AI);
612eb11fae6SDimitry Andric                 LLVM_DEBUG(dbgs() << "   Include (parameter): ");
613eb11fae6SDimitry Andric                 LLVM_DEBUG(SI->print(dbgs()));
614eb11fae6SDimitry Andric                 LLVM_DEBUG(dbgs() << "\n");
61571d5a254SDimitry Andric                 PDIRelated.insert(SI);
616eb11fae6SDimitry Andric                 LLVM_DEBUG(dbgs() << "  Include: ");
617ac9a064cSDimitry Andric                 LLVM_DEBUG(DbgDecl->print(dbgs()));
618eb11fae6SDimitry Andric                 LLVM_DEBUG(dbgs() << "\n");
619ac9a064cSDimitry Andric                 Container.insert(DbgDecl);
62071d5a254SDimitry Andric               } else {
621eb11fae6SDimitry Andric                 LLVM_DEBUG(dbgs() << "   Delete (!parameter): ");
622eb11fae6SDimitry Andric                 LLVM_DEBUG(SI->print(dbgs()));
623eb11fae6SDimitry Andric                 LLVM_DEBUG(dbgs() << "\n");
62471d5a254SDimitry Andric               }
62571d5a254SDimitry Andric             }
62671d5a254SDimitry Andric           } else {
627eb11fae6SDimitry Andric             LLVM_DEBUG(dbgs() << "   Defer: ");
628eb11fae6SDimitry Andric             LLVM_DEBUG(U->print(dbgs()));
629eb11fae6SDimitry Andric             LLVM_DEBUG(dbgs() << "\n");
63071d5a254SDimitry Andric           }
63171d5a254SDimitry Andric         }
63271d5a254SDimitry Andric       } else {
633eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "  Delete (alloca NULL): ");
634ac9a064cSDimitry Andric         LLVM_DEBUG(DbgDecl->print(dbgs()));
635eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "\n");
63671d5a254SDimitry Andric       }
63771d5a254SDimitry Andric     } else {
638eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "  Delete (!parameter): ");
639ac9a064cSDimitry Andric       LLVM_DEBUG(DbgDecl->print(dbgs()));
640eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
64171d5a254SDimitry Andric     }
642ac9a064cSDimitry Andric   };
643ac9a064cSDimitry Andric 
644ac9a064cSDimitry Andric   for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
645ac9a064cSDimitry Andric        BI != BIE; ++BI) {
646ac9a064cSDimitry Andric     // Examine DbgVariableRecords as they happen "before" the instruction. Are
647ac9a064cSDimitry Andric     // they connected to parameters?
648ac9a064cSDimitry Andric     for (DbgVariableRecord &DVR : filterDbgVars(BI->getDbgRecordRange())) {
649ac9a064cSDimitry Andric       if (DVR.isDbgValue() || DVR.isDbgAssign()) {
650ac9a064cSDimitry Andric         ExamineDbgValue(&DVR, PDVRRelated);
651ac9a064cSDimitry Andric       } else {
652ac9a064cSDimitry Andric         assert(DVR.isDbgDeclare());
653ac9a064cSDimitry Andric         ExamineDbgDeclare(&DVR, PDVRRelated);
654ac9a064cSDimitry Andric       }
655ac9a064cSDimitry Andric     }
656ac9a064cSDimitry Andric 
657ac9a064cSDimitry Andric     if (auto *DVI = dyn_cast<DbgValueInst>(&*BI)) {
658ac9a064cSDimitry Andric       ExamineDbgValue(DVI, PDIRelated);
659ac9a064cSDimitry Andric     } else if (auto *DDI = dyn_cast<DbgDeclareInst>(&*BI)) {
660ac9a064cSDimitry Andric       ExamineDbgDeclare(DDI, PDIRelated);
661d8e91e46SDimitry Andric     } else if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
662eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
663eb11fae6SDimitry Andric       LLVM_DEBUG(BI->print(dbgs()));
664eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
66571d5a254SDimitry Andric       PDIRelated.insert(&*BI);
66671d5a254SDimitry Andric     } else {
667eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << " Defer: ");
668eb11fae6SDimitry Andric       LLVM_DEBUG(BI->print(dbgs()));
669eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
67071d5a254SDimitry Andric     }
67171d5a254SDimitry Andric   }
672eb11fae6SDimitry Andric   LLVM_DEBUG(
673eb11fae6SDimitry Andric       dbgs()
67471d5a254SDimitry Andric       << " Report parameter debug info related/related instructions: {\n");
675ac9a064cSDimitry Andric 
676ac9a064cSDimitry Andric   auto IsPDIRelated = [](auto *Rec, auto &Container, auto &UnrelatedCont) {
677ac9a064cSDimitry Andric     if (Container.find(Rec) == Container.end()) {
678eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "  !PDIRelated: ");
679ac9a064cSDimitry Andric       LLVM_DEBUG(Rec->print(dbgs()));
680eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
681ac9a064cSDimitry Andric       UnrelatedCont.push_back(Rec);
68271d5a254SDimitry Andric     } else {
683eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "   PDIRelated: ");
684ac9a064cSDimitry Andric       LLVM_DEBUG(Rec->print(dbgs()));
685eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "\n");
68671d5a254SDimitry Andric     }
687ac9a064cSDimitry Andric   };
688ac9a064cSDimitry Andric 
689ac9a064cSDimitry Andric   // Collect the set of unrelated instructions and debug records.
690ac9a064cSDimitry Andric   for (Instruction &I : *GEntryBlock) {
691ac9a064cSDimitry Andric     for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
692ac9a064cSDimitry Andric       IsPDIRelated(&DVR, PDVRRelated, PDVRUnrelatedWL);
693ac9a064cSDimitry Andric     IsPDIRelated(&I, PDIRelated, PDIUnrelatedWL);
69471d5a254SDimitry Andric   }
695eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << " }\n");
696eb11fae6SDimitry Andric }
697eb11fae6SDimitry Andric 
698e6d15924SDimitry Andric /// Whether this function may be replaced by a forwarding thunk.
canCreateThunkFor(Function * F)699e6d15924SDimitry Andric static bool canCreateThunkFor(Function *F) {
700e6d15924SDimitry Andric   if (F->isVarArg())
701e6d15924SDimitry Andric     return false;
702e6d15924SDimitry Andric 
703eb11fae6SDimitry Andric   // Don't merge tiny functions using a thunk, since it can just end up
704eb11fae6SDimitry Andric   // making the function larger.
705eb11fae6SDimitry Andric   if (F->size() == 1) {
706b1c73532SDimitry Andric     if (F->front().sizeWithoutDebug() < 2) {
707e6d15924SDimitry Andric       LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
708eb11fae6SDimitry Andric                         << " is too small to bother creating a thunk for\n");
709eb11fae6SDimitry Andric       return false;
710eb11fae6SDimitry Andric     }
711eb11fae6SDimitry Andric   }
712eb11fae6SDimitry Andric   return true;
71371d5a254SDimitry Andric }
71471d5a254SDimitry Andric 
715ac9a064cSDimitry Andric /// Copy all metadata of a specific kind from one function to another.
copyMetadataIfPresent(Function * From,Function * To,StringRef Kind)716ac9a064cSDimitry Andric static void copyMetadataIfPresent(Function *From, Function *To,
717ac9a064cSDimitry Andric                                   StringRef Kind) {
718ac9a064cSDimitry Andric   SmallVector<MDNode *, 4> MDs;
719ac9a064cSDimitry Andric   From->getMetadata(Kind, MDs);
720ac9a064cSDimitry Andric   for (MDNode *MD : MDs)
721ac9a064cSDimitry Andric     To->addMetadata(Kind, *MD);
722b1c73532SDimitry Andric }
723b1c73532SDimitry Andric 
72471d5a254SDimitry Andric // Replace G with a simple tail call to bitcast(F). Also (unless
72571d5a254SDimitry Andric // MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
72671d5a254SDimitry Andric // delete G. Under MergeFunctionsPDI, we use G itself for creating
72771d5a254SDimitry Andric // the thunk as we preserve the debug info (and associated instructions)
72871d5a254SDimitry Andric // from G's entry block pertaining to G's incoming arguments which are
72971d5a254SDimitry Andric // passed on as corresponding arguments in the call that G makes to F.
73071d5a254SDimitry Andric // For better debugability, under MergeFunctionsPDI, we do not modify G's
73171d5a254SDimitry Andric // call sites to point to F even when within the same translation unit.
writeThunk(Function * F,Function * G)732cf099d11SDimitry Andric void MergeFunctions::writeThunk(Function *F, Function *G) {
73371d5a254SDimitry Andric   BasicBlock *GEntryBlock = nullptr;
73471d5a254SDimitry Andric   std::vector<Instruction *> PDIUnrelatedWL;
735ac9a064cSDimitry Andric   std::vector<DbgVariableRecord *> PDVRUnrelatedWL;
73671d5a254SDimitry Andric   BasicBlock *BB = nullptr;
73771d5a254SDimitry Andric   Function *NewG = nullptr;
73871d5a254SDimitry Andric   if (MergeFunctionsPDI) {
739eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
74071d5a254SDimitry Andric                          "function as thunk; retain original: "
74171d5a254SDimitry Andric                       << G->getName() << "()\n");
74271d5a254SDimitry Andric     GEntryBlock = &G->getEntryBlock();
743eb11fae6SDimitry Andric     LLVM_DEBUG(
744eb11fae6SDimitry Andric         dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
74571d5a254SDimitry Andric                   "debug info for "
74671d5a254SDimitry Andric                << G->getName() << "() {\n");
747ac9a064cSDimitry Andric     filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL, PDVRUnrelatedWL);
74871d5a254SDimitry Andric     GEntryBlock->getTerminator()->eraseFromParent();
74971d5a254SDimitry Andric     BB = GEntryBlock;
75071d5a254SDimitry Andric   } else {
751d8e91e46SDimitry Andric     NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
752d8e91e46SDimitry Andric                             G->getAddressSpace(), "", G->getParent());
753e6d15924SDimitry Andric     NewG->setComdat(G->getComdat());
754ac9a064cSDimitry Andric     NewG->IsNewDbgInfoFormat = G->IsNewDbgInfoFormat;
75571d5a254SDimitry Andric     BB = BasicBlock::Create(F->getContext(), "", NewG);
75671d5a254SDimitry Andric   }
757600c6fa1SEd Schouten 
75871d5a254SDimitry Andric   IRBuilder<> Builder(BB);
75971d5a254SDimitry Andric   Function *H = MergeFunctionsPDI ? G : NewG;
760abdf259dSRoman Divacky   SmallVector<Value *, 16> Args;
761600c6fa1SEd Schouten   unsigned i = 0;
76230815c53SDimitry Andric   FunctionType *FFTy = F->getFunctionType();
76371d5a254SDimitry Andric   for (Argument &AI : H->args()) {
764dd58ef01SDimitry Andric     Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i)));
765600c6fa1SEd Schouten     ++i;
766600c6fa1SEd Schouten   }
767600c6fa1SEd Schouten 
768411bd29eSDimitry Andric   CallInst *CI = Builder.CreateCall(F, Args);
76971d5a254SDimitry Andric   ReturnInst *RI = nullptr;
770344a3780SDimitry Andric   bool isSwiftTailCall = F->getCallingConv() == CallingConv::SwiftTail &&
771344a3780SDimitry Andric                          G->getCallingConv() == CallingConv::SwiftTail;
772344a3780SDimitry Andric   CI->setTailCallKind(isSwiftTailCall ? llvm::CallInst::TCK_MustTail
773344a3780SDimitry Andric                                       : llvm::CallInst::TCK_Tail);
774600c6fa1SEd Schouten   CI->setCallingConv(F->getCallingConv());
775dd58ef01SDimitry Andric   CI->setAttributes(F->getAttributes());
77671d5a254SDimitry Andric   if (H->getReturnType()->isVoidTy()) {
77771d5a254SDimitry Andric     RI = Builder.CreateRetVoid();
778600c6fa1SEd Schouten   } else {
77971d5a254SDimitry Andric     RI = Builder.CreateRet(createCast(Builder, CI, H->getReturnType()));
780600c6fa1SEd Schouten   }
781600c6fa1SEd Schouten 
78271d5a254SDimitry Andric   if (MergeFunctionsPDI) {
78371d5a254SDimitry Andric     DISubprogram *DIS = G->getSubprogram();
78471d5a254SDimitry Andric     if (DIS) {
785b60736ecSDimitry Andric       DebugLoc CIDbgLoc =
786b60736ecSDimitry Andric           DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
787b60736ecSDimitry Andric       DebugLoc RIDbgLoc =
788b60736ecSDimitry Andric           DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
78971d5a254SDimitry Andric       CI->setDebugLoc(CIDbgLoc);
79071d5a254SDimitry Andric       RI->setDebugLoc(RIDbgLoc);
79171d5a254SDimitry Andric     } else {
792eb11fae6SDimitry Andric       LLVM_DEBUG(
793eb11fae6SDimitry Andric           dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
79471d5a254SDimitry Andric                  << G->getName() << "()\n");
79571d5a254SDimitry Andric     }
79671d5a254SDimitry Andric     eraseTail(G);
797ac9a064cSDimitry Andric     eraseInstsUnrelatedToPDI(PDIUnrelatedWL, PDVRUnrelatedWL);
798eb11fae6SDimitry Andric     LLVM_DEBUG(
799eb11fae6SDimitry Andric         dbgs() << "} // End of parameter related debug info filtering for: "
80071d5a254SDimitry Andric                << G->getName() << "()\n");
80171d5a254SDimitry Andric   } else {
802600c6fa1SEd Schouten     NewG->copyAttributesFrom(G);
803600c6fa1SEd Schouten     NewG->takeName(G);
804b1c73532SDimitry Andric     // Ensure CFI type metadata is propagated to the new function.
805b1c73532SDimitry Andric     copyMetadataIfPresent(G, NewG, "type");
806b1c73532SDimitry Andric     copyMetadataIfPresent(G, NewG, "kcfi_type");
807cf099d11SDimitry Andric     removeUsers(G);
808600c6fa1SEd Schouten     G->replaceAllUsesWith(NewG);
809600c6fa1SEd Schouten     G->eraseFromParent();
81071d5a254SDimitry Andric   }
811cf099d11SDimitry Andric 
812eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
813cf099d11SDimitry Andric   ++NumThunksWritten;
814600c6fa1SEd Schouten }
815600c6fa1SEd Schouten 
816d8e91e46SDimitry Andric // Whether this function may be replaced by an alias
canCreateAliasFor(Function * F)817d8e91e46SDimitry Andric static bool canCreateAliasFor(Function *F) {
818d8e91e46SDimitry Andric   if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
819d8e91e46SDimitry Andric     return false;
820d8e91e46SDimitry Andric 
821d8e91e46SDimitry Andric   // We should only see linkages supported by aliases here
822d8e91e46SDimitry Andric   assert(F->hasLocalLinkage() || F->hasExternalLinkage()
823d8e91e46SDimitry Andric       || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
824d8e91e46SDimitry Andric   return true;
825d8e91e46SDimitry Andric }
826d8e91e46SDimitry Andric 
827d8e91e46SDimitry Andric // Replace G with an alias to F (deleting function G)
writeAlias(Function * F,Function * G)828d8e91e46SDimitry Andric void MergeFunctions::writeAlias(Function *F, Function *G) {
829d8e91e46SDimitry Andric   PointerType *PtrType = G->getType();
830344a3780SDimitry Andric   auto *GA = GlobalAlias::create(G->getValueType(), PtrType->getAddressSpace(),
831b1c73532SDimitry Andric                                  G->getLinkage(), "", F, G->getParent());
832d8e91e46SDimitry Andric 
833e3b55780SDimitry Andric   const MaybeAlign FAlign = F->getAlign();
834e3b55780SDimitry Andric   const MaybeAlign GAlign = G->getAlign();
835e3b55780SDimitry Andric   if (FAlign || GAlign)
836e3b55780SDimitry Andric     F->setAlignment(std::max(FAlign.valueOrOne(), GAlign.valueOrOne()));
837e3b55780SDimitry Andric   else
838e3b55780SDimitry Andric     F->setAlignment(std::nullopt);
839d8e91e46SDimitry Andric   GA->takeName(G);
840d8e91e46SDimitry Andric   GA->setVisibility(G->getVisibility());
841d8e91e46SDimitry Andric   GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
842d8e91e46SDimitry Andric 
843d8e91e46SDimitry Andric   removeUsers(G);
844d8e91e46SDimitry Andric   G->replaceAllUsesWith(GA);
845d8e91e46SDimitry Andric   G->eraseFromParent();
846d8e91e46SDimitry Andric 
847d8e91e46SDimitry Andric   LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
848d8e91e46SDimitry Andric   ++NumAliasesWritten;
849d8e91e46SDimitry Andric }
850d8e91e46SDimitry Andric 
851d8e91e46SDimitry Andric // Replace G with an alias to F if possible, or a thunk to F if
852d8e91e46SDimitry Andric // profitable. Returns false if neither is the case.
writeThunkOrAlias(Function * F,Function * G)853d8e91e46SDimitry Andric bool MergeFunctions::writeThunkOrAlias(Function *F, Function *G) {
854d8e91e46SDimitry Andric   if (canCreateAliasFor(G)) {
855d8e91e46SDimitry Andric     writeAlias(F, G);
856d8e91e46SDimitry Andric     return true;
857d8e91e46SDimitry Andric   }
858e6d15924SDimitry Andric   if (canCreateThunkFor(F)) {
859d8e91e46SDimitry Andric     writeThunk(F, G);
860d8e91e46SDimitry Andric     return true;
861d8e91e46SDimitry Andric   }
862d8e91e46SDimitry Andric   return false;
863d8e91e46SDimitry Andric }
864d8e91e46SDimitry Andric 
865cf099d11SDimitry Andric // Merge two equivalent functions. Upon completion, Function G is deleted.
mergeTwoFunctions(Function * F,Function * G)866cf099d11SDimitry Andric void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
86701095a5dSDimitry Andric   if (F->isInterposable()) {
86801095a5dSDimitry Andric     assert(G->isInterposable());
869cf099d11SDimitry Andric 
870d8e91e46SDimitry Andric     // Both writeThunkOrAlias() calls below must succeed, either because we can
871d8e91e46SDimitry Andric     // create aliases for G and NewF, or because a thunk for F is profitable.
872d8e91e46SDimitry Andric     // F here has the same signature as NewF below, so that's what we check.
873e6d15924SDimitry Andric     if (!canCreateThunkFor(F) &&
874e6d15924SDimitry Andric         (!canCreateAliasFor(F) || !canCreateAliasFor(G)))
875eb11fae6SDimitry Andric       return;
876eb11fae6SDimitry Andric 
877600c6fa1SEd Schouten     // Make them both thunks to the same internal function.
878d8e91e46SDimitry Andric     Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
879d8e91e46SDimitry Andric                                       F->getAddressSpace(), "", F->getParent());
880d8e91e46SDimitry Andric     NewF->copyAttributesFrom(F);
881d8e91e46SDimitry Andric     NewF->takeName(F);
882ac9a064cSDimitry Andric     NewF->IsNewDbgInfoFormat = F->IsNewDbgInfoFormat;
883b1c73532SDimitry Andric     // Ensure CFI type metadata is propagated to the new function.
884b1c73532SDimitry Andric     copyMetadataIfPresent(F, NewF, "type");
885b1c73532SDimitry Andric     copyMetadataIfPresent(F, NewF, "kcfi_type");
886cf099d11SDimitry Andric     removeUsers(F);
887d8e91e46SDimitry Andric     F->replaceAllUsesWith(NewF);
888009b1c42SEd Schouten 
889e3b55780SDimitry Andric     // We collect alignment before writeThunkOrAlias that overwrites NewF and
890e3b55780SDimitry Andric     // G's content.
891e3b55780SDimitry Andric     const MaybeAlign NewFAlign = NewF->getAlign();
892e3b55780SDimitry Andric     const MaybeAlign GAlign = G->getAlign();
893600c6fa1SEd Schouten 
894d8e91e46SDimitry Andric     writeThunkOrAlias(F, G);
895d8e91e46SDimitry Andric     writeThunkOrAlias(F, NewF);
896d39c594dSDimitry Andric 
897e3b55780SDimitry Andric     if (NewFAlign || GAlign)
898e3b55780SDimitry Andric       F->setAlignment(std::max(NewFAlign.valueOrOne(), GAlign.valueOrOne()));
899e3b55780SDimitry Andric     else
900e3b55780SDimitry Andric       F->setAlignment(std::nullopt);
901cf099d11SDimitry Andric     F->setLinkage(GlobalValue::PrivateLinkage);
902cf099d11SDimitry Andric     ++NumDoubleWeak;
903eb11fae6SDimitry Andric     ++NumFunctionsMerged;
904cf099d11SDimitry Andric   } else {
905eb11fae6SDimitry Andric     // For better debugability, under MergeFunctionsPDI, we do not modify G's
906eb11fae6SDimitry Andric     // call sites to point to F even when within the same translation unit.
907eb11fae6SDimitry Andric     if (!G->isInterposable() && !MergeFunctionsPDI) {
908145449b1SDimitry Andric       // Functions referred to by llvm.used/llvm.compiler.used are special:
909145449b1SDimitry Andric       // there are uses of the symbol name that are not visible to LLVM,
910145449b1SDimitry Andric       // usually from inline asm.
911145449b1SDimitry Andric       if (G->hasGlobalUnnamedAddr() && !Used.contains(G)) {
912eb11fae6SDimitry Andric         // G might have been a key in our GlobalNumberState, and it's illegal
913eb11fae6SDimitry Andric         // to replace a key in ValueMap<GlobalValue *> with a non-global.
914eb11fae6SDimitry Andric         GlobalNumbers.erase(G);
915eb11fae6SDimitry Andric         // If G's address is not significant, replace it entirely.
916d8e91e46SDimitry Andric         removeUsers(G);
917b1c73532SDimitry Andric         G->replaceAllUsesWith(F);
918eb11fae6SDimitry Andric       } else {
919eb11fae6SDimitry Andric         // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
920eb11fae6SDimitry Andric         // above).
921eb11fae6SDimitry Andric         replaceDirectCallers(G, F);
922eb11fae6SDimitry Andric       }
923600c6fa1SEd Schouten     }
924009b1c42SEd Schouten 
925eb11fae6SDimitry Andric     // If G was internal then we may have replaced all uses of G with F. If so,
926eb11fae6SDimitry Andric     // stop here and delete G. There's no need for a thunk. (See note on
927eb11fae6SDimitry Andric     // MergeFunctionsPDI above).
928d8e91e46SDimitry Andric     if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
929eb11fae6SDimitry Andric       G->eraseFromParent();
930009b1c42SEd Schouten       ++NumFunctionsMerged;
931eb11fae6SDimitry Andric       return;
932eb11fae6SDimitry Andric     }
933eb11fae6SDimitry Andric 
934d8e91e46SDimitry Andric     if (writeThunkOrAlias(F, G)) {
935eb11fae6SDimitry Andric       ++NumFunctionsMerged;
936eb11fae6SDimitry Andric     }
937009b1c42SEd Schouten   }
938d8e91e46SDimitry Andric }
939009b1c42SEd Schouten 
940dd58ef01SDimitry Andric /// Replace function F by function G.
replaceFunctionInTree(const FunctionNode & FN,Function * G)941dd58ef01SDimitry Andric void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
94285d8b2bbSDimitry Andric                                            Function *G) {
943dd58ef01SDimitry Andric   Function *F = FN.getFunc();
944dd58ef01SDimitry Andric   assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
945dd58ef01SDimitry Andric          "The two functions must be equal");
94685d8b2bbSDimitry Andric 
947dd58ef01SDimitry Andric   auto I = FNodesInTree.find(F);
948dd58ef01SDimitry Andric   assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
949dd58ef01SDimitry Andric   assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
95085d8b2bbSDimitry Andric 
951dd58ef01SDimitry Andric   FnTreeType::iterator IterToFNInFnTree = I->second;
952dd58ef01SDimitry Andric   assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
953dd58ef01SDimitry Andric   // Remove F -> FN and insert G -> FN
954dd58ef01SDimitry Andric   FNodesInTree.erase(I);
955dd58ef01SDimitry Andric   FNodesInTree.insert({G, IterToFNInFnTree});
956dd58ef01SDimitry Andric   // Replace F with G in FN, which is stored inside the FnTree.
957dd58ef01SDimitry Andric   FN.replaceBy(G);
95885d8b2bbSDimitry Andric }
95985d8b2bbSDimitry Andric 
960d8e91e46SDimitry Andric // Ordering for functions that are equal under FunctionComparator
isFuncOrderCorrect(const Function * F,const Function * G)961d8e91e46SDimitry Andric static bool isFuncOrderCorrect(const Function *F, const Function *G) {
962d8e91e46SDimitry Andric   if (F->isInterposable() != G->isInterposable()) {
963d8e91e46SDimitry Andric     // Strong before weak, because the weak function may call the strong
964d8e91e46SDimitry Andric     // one, but not the other way around.
965d8e91e46SDimitry Andric     return !F->isInterposable();
966d8e91e46SDimitry Andric   }
967d8e91e46SDimitry Andric   if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
968d8e91e46SDimitry Andric     // External before local, because we definitely have to keep the external
969d8e91e46SDimitry Andric     // function, but may be able to drop the local one.
970d8e91e46SDimitry Andric     return !F->hasLocalLinkage();
971d8e91e46SDimitry Andric   }
972d8e91e46SDimitry Andric   // Impose a total order (by name) on the replacement of functions. This is
973d8e91e46SDimitry Andric   // important when operating on more than one module independently to prevent
974d8e91e46SDimitry Andric   // cycles of thunks calling each other when the modules are linked together.
975d8e91e46SDimitry Andric   return F->getName() <= G->getName();
976d8e91e46SDimitry Andric }
977d8e91e46SDimitry Andric 
9785ca98fd9SDimitry Andric // Insert a ComparableFunction into the FnTree, or merge it away if equal to one
979cf099d11SDimitry Andric // that was already inserted.
insert(Function * NewFunction)9805ca98fd9SDimitry Andric bool MergeFunctions::insert(Function *NewFunction) {
9815ca98fd9SDimitry Andric   std::pair<FnTreeType::iterator, bool> Result =
9825a5ac124SDimitry Andric       FnTree.insert(FunctionNode(NewFunction));
9835ca98fd9SDimitry Andric 
984cf099d11SDimitry Andric   if (Result.second) {
985dd58ef01SDimitry Andric     assert(FNodesInTree.count(NewFunction) == 0);
986dd58ef01SDimitry Andric     FNodesInTree.insert({NewFunction, Result.first});
987eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
988eb11fae6SDimitry Andric                       << '\n');
989cf099d11SDimitry Andric     return false;
990cf099d11SDimitry Andric   }
991009b1c42SEd Schouten 
99267c32a98SDimitry Andric   const FunctionNode &OldF = *Result.first;
993009b1c42SEd Schouten 
994d8e91e46SDimitry Andric   if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
99585d8b2bbSDimitry Andric     // Swap the two functions.
99685d8b2bbSDimitry Andric     Function *F = OldF.getFunc();
997dd58ef01SDimitry Andric     replaceFunctionInTree(*Result.first, NewFunction);
99885d8b2bbSDimitry Andric     NewFunction = F;
99985d8b2bbSDimitry Andric     assert(OldF.getFunc() != F && "Must have swapped the functions.");
100085d8b2bbSDimitry Andric   }
100185d8b2bbSDimitry Andric 
1002eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "  " << OldF.getFunc()->getName()
10035ca98fd9SDimitry Andric                     << " == " << NewFunction->getName() << '\n');
1004d39c594dSDimitry Andric 
10055ca98fd9SDimitry Andric   Function *DeleteF = NewFunction;
1006cf099d11SDimitry Andric   mergeTwoFunctions(OldF.getFunc(), DeleteF);
1007cf099d11SDimitry Andric   return true;
1008cf099d11SDimitry Andric }
1009d39c594dSDimitry Andric 
10105ca98fd9SDimitry Andric // Remove a function from FnTree. If it was already in FnTree, add
10115ca98fd9SDimitry Andric // it to Deferred so that we'll look at it in the next round.
remove(Function * F)1012cf099d11SDimitry Andric void MergeFunctions::remove(Function *F) {
1013dd58ef01SDimitry Andric   auto I = FNodesInTree.find(F);
1014dd58ef01SDimitry Andric   if (I != FNodesInTree.end()) {
1015eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
1016dd58ef01SDimitry Andric     FnTree.erase(I->second);
1017dd58ef01SDimitry Andric     // I->second has been invalidated, remove it from the FNodesInTree map to
1018dd58ef01SDimitry Andric     // preserve the invariant.
1019dd58ef01SDimitry Andric     FNodesInTree.erase(I);
102085d8b2bbSDimitry Andric     Deferred.emplace_back(F);
1021009b1c42SEd Schouten   }
1022009b1c42SEd Schouten }
1023009b1c42SEd Schouten 
1024cf099d11SDimitry Andric // For each instruction used by the value, remove() the function that contains
1025cf099d11SDimitry Andric // the instruction. This should happen right before a call to RAUW.
removeUsers(Value * V)1026cf099d11SDimitry Andric void MergeFunctions::removeUsers(Value *V) {
1027e6d15924SDimitry Andric   for (User *U : V->users())
1028e6d15924SDimitry Andric     if (auto *I = dyn_cast<Instruction>(U))
1029d8e91e46SDimitry Andric       remove(I->getFunction());
1030dd58ef01SDimitry Andric }
1031