AlwaysInliner.cpp 8.0 KB

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