1 //===- InlineAlways.cpp - Code to inline always_inline functions ----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements a custom inliner that handles only functions that 10 // are marked as "always inline". 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/IPO/AlwaysInliner.h" 15 #include "llvm/ADT/SetVector.h" 16 #include "llvm/Analysis/AliasAnalysis.h" 17 #include "llvm/Analysis/AssumptionCache.h" 18 #include "llvm/Analysis/InlineCost.h" 19 #include "llvm/Analysis/ProfileSummaryInfo.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/IR/CallingConv.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/Instructions.h" 24 #include "llvm/IR/Module.h" 25 #include "llvm/IR/Type.h" 26 #include "llvm/InitializePasses.h" 27 #include "llvm/Transforms/IPO.h" 28 #include "llvm/Transforms/IPO/Inliner.h" 29 #include "llvm/Transforms/Utils/Cloning.h" 30 #include "llvm/Transforms/Utils/ModuleUtils.h" 31 32 using namespace llvm; 33 34 #define DEBUG_TYPE "inline" 35 36 PreservedAnalyses AlwaysInlinerPass::run(Module &M, 37 ModuleAnalysisManager &MAM) { 38 // Add inline assumptions during code generation. 39 FunctionAnalysisManager &FAM = 40 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 41 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & { 42 return FAM.getResult<AssumptionAnalysis>(F); 43 }; 44 auto &PSI = MAM.getResult<ProfileSummaryAnalysis>(M); 45 46 SmallSetVector<CallBase *, 16> Calls; 47 bool Changed = false; 48 SmallVector<Function *, 16> InlinedFunctions; 49 for (Function &F : M) 50 if (!F.isDeclaration() && F.hasFnAttribute(Attribute::AlwaysInline) && 51 isInlineViable(F).isSuccess()) { 52 Calls.clear(); 53 54 for (User *U : F.users()) 55 if (auto *CB = dyn_cast<CallBase>(U)) 56 if (CB->getCalledFunction() == &F) 57 Calls.insert(CB); 58 59 for (CallBase *CB : Calls) { 60 Function *Caller = CB->getCaller(); 61 OptimizationRemarkEmitter ORE(Caller); 62 auto OIC = shouldInline( 63 *CB, 64 [&](CallBase &CB) { 65 return InlineCost::getAlways("always inline attribute"); 66 }, 67 ORE); 68 assert(OIC); 69 emitInlinedInto(ORE, CB->getDebugLoc(), CB->getParent(), F, *Caller, 70 *OIC, false, DEBUG_TYPE); 71 72 InlineFunctionInfo IFI( 73 /*cg=*/nullptr, GetAssumptionCache, &PSI, 74 &FAM.getResult<BlockFrequencyAnalysis>(*(CB->getCaller())), 75 &FAM.getResult<BlockFrequencyAnalysis>(F)); 76 77 InlineResult Res = InlineFunction( 78 *CB, IFI, &FAM.getResult<AAManager>(F), InsertLifetime); 79 assert(Res.isSuccess() && "unexpected failure to inline"); 80 (void)Res; 81 82 // Merge the attributes based on the inlining. 83 AttributeFuncs::mergeAttributesForInlining(*Caller, F); 84 85 Changed = true; 86 } 87 88 // Remember to try and delete this function afterward. This both avoids 89 // re-walking the rest of the module and avoids dealing with any iterator 90 // invalidation issues while deleting functions. 91 InlinedFunctions.push_back(&F); 92 } 93 94 // Remove any live functions. 95 erase_if(InlinedFunctions, [&](Function *F) { 96 F->removeDeadConstantUsers(); 97 return !F->isDefTriviallyDead(); 98 }); 99 100 // Delete the non-comdat ones from the module and also from our vector. 101 auto NonComdatBegin = partition( 102 InlinedFunctions, [&](Function *F) { return F->hasComdat(); }); 103 for (Function *F : make_range(NonComdatBegin, InlinedFunctions.end())) 104 M.getFunctionList().erase(F); 105 InlinedFunctions.erase(NonComdatBegin, InlinedFunctions.end()); 106 107 if (!InlinedFunctions.empty()) { 108 // Now we just have the comdat functions. Filter out the ones whose comdats 109 // are not actually dead. 110 filterDeadComdatFunctions(M, InlinedFunctions); 111 // The remaining functions are actually dead. 112 for (Function *F : InlinedFunctions) 113 M.getFunctionList().erase(F); 114 } 115 116 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all(); 117 } 118 119 namespace { 120 121 /// Inliner pass which only handles "always inline" functions. 122 /// 123 /// Unlike the \c AlwaysInlinerPass, this uses the more heavyweight \c Inliner 124 /// base class to provide several facilities such as array alloca merging. 125 class AlwaysInlinerLegacyPass : public LegacyInlinerBase { 126 127 public: 128 AlwaysInlinerLegacyPass() : LegacyInlinerBase(ID, /*InsertLifetime*/ true) { 129 initializeAlwaysInlinerLegacyPassPass(*PassRegistry::getPassRegistry()); 130 } 131 132 AlwaysInlinerLegacyPass(bool InsertLifetime) 133 : LegacyInlinerBase(ID, InsertLifetime) { 134 initializeAlwaysInlinerLegacyPassPass(*PassRegistry::getPassRegistry()); 135 } 136 137 /// Main run interface method. We override here to avoid calling skipSCC(). 138 bool runOnSCC(CallGraphSCC &SCC) override { return inlineCalls(SCC); } 139 140 static char ID; // Pass identification, replacement for typeid 141 142 InlineCost getInlineCost(CallBase &CB) override; 143 144 using llvm::Pass::doFinalization; 145 bool doFinalization(CallGraph &CG) override { 146 return removeDeadFunctions(CG, /*AlwaysInlineOnly=*/true); 147 } 148 }; 149 } 150 151 char AlwaysInlinerLegacyPass::ID = 0; 152 INITIALIZE_PASS_BEGIN(AlwaysInlinerLegacyPass, "always-inline", 153 "Inliner for always_inline functions", false, false) 154 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 155 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 156 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 157 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 158 INITIALIZE_PASS_END(AlwaysInlinerLegacyPass, "always-inline", 159 "Inliner for always_inline functions", false, false) 160 161 Pass *llvm::createAlwaysInlinerLegacyPass(bool InsertLifetime) { 162 return new AlwaysInlinerLegacyPass(InsertLifetime); 163 } 164 165 /// Get the inline cost for the always-inliner. 166 /// 167 /// The always inliner *only* handles functions which are marked with the 168 /// attribute to force inlining. As such, it is dramatically simpler and avoids 169 /// using the powerful (but expensive) inline cost analysis. Instead it uses 170 /// a very simple and boring direct walk of the instructions looking for 171 /// impossible-to-inline constructs. 172 /// 173 /// Note, it would be possible to go to some lengths to cache the information 174 /// computed here, but as we only expect to do this for relatively few and 175 /// small functions which have the explicit attribute to force inlining, it is 176 /// likely not worth it in practice. 177 InlineCost AlwaysInlinerLegacyPass::getInlineCost(CallBase &CB) { 178 Function *Callee = CB.getCalledFunction(); 179 180 // Only inline direct calls to functions with always-inline attributes 181 // that are viable for inlining. 182 if (!Callee) 183 return InlineCost::getNever("indirect call"); 184 185 // FIXME: We shouldn't even get here for declarations. 186 if (Callee->isDeclaration()) 187 return InlineCost::getNever("no definition"); 188 189 if (!CB.hasFnAttr(Attribute::AlwaysInline)) 190 return InlineCost::getNever("no alwaysinline attribute"); 191 192 auto IsViable = isInlineViable(*Callee); 193 if (!IsViable.isSuccess()) 194 return InlineCost::getNever(IsViable.getFailureReason()); 195 196 return InlineCost::getAlways("always inliner"); 197 } 198