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