LLVM  10.0.0
AlwaysInliner.cpp
Go to the documentation of this file.
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 
15 #include "llvm/ADT/SetVector.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"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "inline"
34 
36  ModuleAnalysisManager &MAM) {
37  // Add inline assumptions during code generation.
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 
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)) {
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 
65  // Remember to try and delete this function afterward. This both avoids
66  // re-walking the rest of the module and avoids dealing with any iterator
67  // invalidation issues while deleting functions.
68  InlinedFunctions.push_back(&F);
69  }
70 
71  // Remove any live functions.
72  erase_if(InlinedFunctions, [&](Function *F) {
74  return !F->isDefTriviallyDead();
75  });
76 
77  // Delete the non-comdat ones from the module and also from our vector.
78  auto NonComdatBegin = partition(
79  InlinedFunctions, [&](Function *F) { return F->hasComdat(); });
80  for (Function *F : make_range(NonComdatBegin, InlinedFunctions.end()))
81  M.getFunctionList().erase(F);
82  InlinedFunctions.erase(NonComdatBegin, InlinedFunctions.end());
83 
84  if (!InlinedFunctions.empty()) {
85  // Now we just have the comdat functions. Filter out the ones whose comdats
86  // are not actually dead.
87  filterDeadComdatFunctions(M, InlinedFunctions);
88  // The remaining functions are actually dead.
89  for (Function *F : InlinedFunctions)
90  M.getFunctionList().erase(F);
91  }
92 
93  return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
94 }
95 
96 namespace {
97 
98 /// Inliner pass which only handles "always inline" functions.
99 ///
100 /// Unlike the \c AlwaysInlinerPass, this uses the more heavyweight \c Inliner
101 /// base class to provide several facilities such as array alloca merging.
102 class AlwaysInlinerLegacyPass : public LegacyInlinerBase {
103 
104 public:
105  AlwaysInlinerLegacyPass() : LegacyInlinerBase(ID, /*InsertLifetime*/ true) {
107  }
108 
109  AlwaysInlinerLegacyPass(bool InsertLifetime)
110  : LegacyInlinerBase(ID, InsertLifetime) {
112  }
113 
114  /// Main run interface method. We override here to avoid calling skipSCC().
115  bool runOnSCC(CallGraphSCC &SCC) override { return inlineCalls(SCC); }
116 
117  static char ID; // Pass identification, replacement for typeid
118 
119  InlineCost getInlineCost(CallSite CS) override;
120 
122  bool doFinalization(CallGraph &CG) override {
123  return removeDeadFunctions(CG, /*AlwaysInlineOnly=*/true);
124  }
125 };
126 }
127 
129 INITIALIZE_PASS_BEGIN(AlwaysInlinerLegacyPass, "always-inline",
130  "Inliner for always_inline functions", false, false)
135 INITIALIZE_PASS_END(AlwaysInlinerLegacyPass, "always-inline",
136  "Inliner for always_inline functions", false, false)
137 
138 Pass *llvm::createAlwaysInlinerLegacyPass(bool InsertLifetime) {
139  return new AlwaysInlinerLegacyPass(InsertLifetime);
140 }
141 
142 /// Get the inline cost for the always-inliner.
143 ///
144 /// The always inliner *only* handles functions which are marked with the
145 /// attribute to force inlining. As such, it is dramatically simpler and avoids
146 /// using the powerful (but expensive) inline cost analysis. Instead it uses
147 /// a very simple and boring direct walk of the instructions looking for
148 /// impossible-to-inline constructs.
149 ///
150 /// Note, it would be possible to go to some lengths to cache the information
151 /// computed here, but as we only expect to do this for relatively few and
152 /// small functions which have the explicit attribute to force inlining, it is
153 /// likely not worth it in practice.
156 
157  // Only inline direct calls to functions with always-inline attributes
158  // that are viable for inlining.
159  if (!Callee)
160  return InlineCost::getNever("indirect call");
161 
162  // FIXME: We shouldn't even get here for declarations.
163  if (Callee->isDeclaration())
164  return InlineCost::getNever("no definition");
165 
166  if (!CS.hasFnAttr(Attribute::AlwaysInline))
167  return InlineCost::getNever("no alwaysinline attribute");
168 
169  auto IsViable = isInlineViable(*Callee);
170  if (!IsViable)
171  return InlineCost::getNever(IsViable.message);
172 
173  return InlineCost::getAlways("always inliner");
174 }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:78
InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI, std::function< AssumptionCache &(Function &)> &GetAssumptionCache, Optional< function_ref< BlockFrequencyInfo &(Function &)>> GetBFI, ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:777
partial Partial Inliner
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
INITIALIZE_PASS_BEGIN(AlwaysInlinerLegacyPass, "always-inline", "Inliner for always_inline functions", false, false) INITIALIZE_PASS_END(AlwaysInlinerLegacyPass
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
F(f)
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it&#39;s an indirect...
Definition: CallSite.h:111
This class captures the data input to the InlineFunction call, and records the auxiliary results prod...
Definition: Cloning.h:173
Represents the cost of inlining a function.
Definition: InlineCost.h:63
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
This class contains all of the helper code which is used to perform the inlining operations that do n...
Definition: Inliner.h:30
virtual bool doFinalization(Module &)
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
Definition: Pass.h:107
always Inliner for always_inline functions
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:141
auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::partition which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1271
static InlineCost getAlways(const char *Reason)
Definition: InlineCost.h:91
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Definition: Constants.cpp:600
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:157
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
The ModulePass which wraps up a CallGraph and the logic to build it.
Definition: CallGraph.h:324
InlineResult isInlineViable(Function &Callee)
Minimal filter to detect invalid constructs for inlining.
Pass * createAlwaysInlinerLegacyPass(bool InsertLifetime=true)
Create a legacy pass manager instance of a pass to inline and remove functions marked as "always_inli...
InlineResult InlineFunction(CallBase *CB, InlineFunctionInfo &IFI, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true)
This function inlines the called function into the basic block of the caller.
void initializeAlwaysInlinerLegacyPassPass(PassRegistry &)
iterator erase(const_iterator CI)
Definition: SmallVector.h:434
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Provides passes to inlining "always_inline" functions.
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:297
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Module.h This file contains the declarations for the Module class.
always inline
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2&#39;s erase_if which is equivalent t...
Definition: STLExtras.h:1340
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if this function has the given attribute.
Definition: CallSite.h:370
amdgpu Simplify well known AMD library false FunctionCallee Callee
bool hasComdat() const
Definition: GlobalObject.h:119
void filterDeadComdatFunctions(Module &M, SmallVectorImpl< Function *> &DeadComdatFunctions)
Filter out potentially dead comdat functions where other entries keep the entire comdat group alive...
The basic data container for the call graph of a Module of IR.
Definition: CallGraph.h:73
static InlineCost getNever(const char *Reason)
Definition: InlineCost.h:94
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:231
CallGraphSCC - This is a single SCC that a CallGraphSCCPass is run on.
A container for analyses that lazily runs them and caches their results.
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
bool isDefTriviallyDead() const
isDefTriviallyDead - Return true if it is trivially safe to remove this function definition from the ...
Definition: Function.cpp:1459
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:1045