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/AssumptionCache.h"
17 #include "llvm/Analysis/InlineCost.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/IR/CallSite.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 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "inline"
34 
35 PreservedAnalyses AlwaysInlinerPass::run(Module &M,
36                                          ModuleAnalysisManager &MAM) {
37   // Add inline assumptions during code generation.
38   FunctionAnalysisManager &FAM =
39       MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
40   std::function<AssumptionCache &(Function &)> GetAssumptionCache =
41       [&](Function &F) -> AssumptionCache & {
42     return FAM.getResult<AssumptionAnalysis>(F);
43   };
44   InlineFunctionInfo IFI(/*cg=*/nullptr, &GetAssumptionCache);
45 
46   SmallSetVector<CallSite, 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 CS = CallSite(U))
56           if (CS.getCalledFunction() == &F)
57             Calls.insert(CS);
58 
59       for (CallSite CS : Calls)
60         // FIXME: We really shouldn't be able to fail to inline at this point!
61         // We should do something to log or check the inline failures here.
62         Changed |=
63             InlineFunction(CS, IFI, /*CalleeAAR=*/nullptr, InsertLifetime)
64                 .isSuccess();
65 
66       // Remember to try and delete this function afterward. This both avoids
67       // re-walking the rest of the module and avoids dealing with any iterator
68       // invalidation issues while deleting functions.
69       InlinedFunctions.push_back(&F);
70     }
71 
72   // Remove any live functions.
73   erase_if(InlinedFunctions, [&](Function *F) {
74     F->removeDeadConstantUsers();
75     return !F->isDefTriviallyDead();
76   });
77 
78   // Delete the non-comdat ones from the module and also from our vector.
79   auto NonComdatBegin = partition(
80       InlinedFunctions, [&](Function *F) { return F->hasComdat(); });
81   for (Function *F : make_range(NonComdatBegin, InlinedFunctions.end()))
82     M.getFunctionList().erase(F);
83   InlinedFunctions.erase(NonComdatBegin, InlinedFunctions.end());
84 
85   if (!InlinedFunctions.empty()) {
86     // Now we just have the comdat functions. Filter out the ones whose comdats
87     // are not actually dead.
88     filterDeadComdatFunctions(M, InlinedFunctions);
89     // The remaining functions are actually dead.
90     for (Function *F : InlinedFunctions)
91       M.getFunctionList().erase(F);
92   }
93 
94   return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
95 }
96 
97 namespace {
98 
99 /// Inliner pass which only handles "always inline" functions.
100 ///
101 /// Unlike the \c AlwaysInlinerPass, this uses the more heavyweight \c Inliner
102 /// base class to provide several facilities such as array alloca merging.
103 class AlwaysInlinerLegacyPass : public LegacyInlinerBase {
104 
105 public:
106   AlwaysInlinerLegacyPass() : LegacyInlinerBase(ID, /*InsertLifetime*/ true) {
107     initializeAlwaysInlinerLegacyPassPass(*PassRegistry::getPassRegistry());
108   }
109 
110   AlwaysInlinerLegacyPass(bool InsertLifetime)
111       : LegacyInlinerBase(ID, InsertLifetime) {
112     initializeAlwaysInlinerLegacyPassPass(*PassRegistry::getPassRegistry());
113   }
114 
115   /// Main run interface method.  We override here to avoid calling skipSCC().
116   bool runOnSCC(CallGraphSCC &SCC) override { return inlineCalls(SCC); }
117 
118   static char ID; // Pass identification, replacement for typeid
119 
120   InlineCost getInlineCost(CallSite CS) override;
121 
122   using llvm::Pass::doFinalization;
123   bool doFinalization(CallGraph &CG) override {
124     return removeDeadFunctions(CG, /*AlwaysInlineOnly=*/true);
125   }
126 };
127 }
128 
129 char AlwaysInlinerLegacyPass::ID = 0;
130 INITIALIZE_PASS_BEGIN(AlwaysInlinerLegacyPass, "always-inline",
131                       "Inliner for always_inline functions", false, false)
132 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
133 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
134 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
135 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
136 INITIALIZE_PASS_END(AlwaysInlinerLegacyPass, "always-inline",
137                     "Inliner for always_inline functions", false, false)
138 
139 Pass *llvm::createAlwaysInlinerLegacyPass(bool InsertLifetime) {
140   return new AlwaysInlinerLegacyPass(InsertLifetime);
141 }
142 
143 /// Get the inline cost for the always-inliner.
144 ///
145 /// The always inliner *only* handles functions which are marked with the
146 /// attribute to force inlining. As such, it is dramatically simpler and avoids
147 /// using the powerful (but expensive) inline cost analysis. Instead it uses
148 /// a very simple and boring direct walk of the instructions looking for
149 /// impossible-to-inline constructs.
150 ///
151 /// Note, it would be possible to go to some lengths to cache the information
152 /// computed here, but as we only expect to do this for relatively few and
153 /// small functions which have the explicit attribute to force inlining, it is
154 /// likely not worth it in practice.
155 InlineCost AlwaysInlinerLegacyPass::getInlineCost(CallSite CS) {
156   Function *Callee = CS.getCalledFunction();
157 
158   // Only inline direct calls to functions with always-inline attributes
159   // that are viable for inlining.
160   if (!Callee)
161     return InlineCost::getNever("indirect call");
162 
163   // FIXME: We shouldn't even get here for declarations.
164   if (Callee->isDeclaration())
165     return InlineCost::getNever("no definition");
166 
167   if (!CS.hasFnAttr(Attribute::AlwaysInline))
168     return InlineCost::getNever("no alwaysinline attribute");
169 
170   auto IsViable = isInlineViable(*Callee);
171   if (!IsViable.isSuccess())
172     return InlineCost::getNever(IsViable.getFailureReason());
173 
174   return InlineCost::getAlways("always inliner");
175 }
176