1 //===- InlineAdvisor.cpp - analysis pass implementation -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements InlineAdvisorAnalysis and DefaultInlineAdvisor, and
11 // related types.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Analysis/InlineAdvisor.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/InlineCost.h"
18 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
19 #include "llvm/Analysis/ProfileSummaryInfo.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/Support/raw_ostream.h"
24 
25 #include <sstream>
26 
27 using namespace llvm;
28 #define DEBUG_TYPE "inline"
29 
30 // This weirdly named statistic tracks the number of times that, when attempting
31 // to inline a function A into B, we analyze the callers of B in order to see
32 // if those would be more profitable and blocked inline steps.
33 STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
34 
35 /// Flag to add inline messages as callsite attributes 'inline-remark'.
36 static cl::opt<bool>
37     InlineRemarkAttribute("inline-remark-attribute", cl::init(false),
38                           cl::Hidden,
39                           cl::desc("Enable adding inline-remark attribute to"
40                                    " callsites processed by inliner but decided"
41                                    " to be not inlined"));
42 
43 // An integer used to limit the cost of inline deferral.  The default negative
44 // number tells shouldBeDeferred to only take the secondary cost into account.
45 static cl::opt<int>
46     InlineDeferralScale("inline-deferral-scale",
47                         cl::desc("Scale to limit the cost of inline deferral"),
48                         cl::init(2), cl::Hidden);
49 
50 namespace {
51 class DefaultInlineAdvice : public InlineAdvice {
52 public:
53   DefaultInlineAdvice(DefaultInlineAdvisor *Advisor, CallBase &CB,
54                       Optional<InlineCost> OIC, OptimizationRemarkEmitter &ORE)
55       : InlineAdvice(Advisor, CB, ORE, OIC.hasValue()), OriginalCB(&CB),
56         OIC(OIC) {}
57 
58 private:
59   void recordUnsuccessfulInliningImpl(const InlineResult &Result) override {
60     using namespace ore;
61     llvm::setInlineRemark(*OriginalCB, std::string(Result.getFailureReason()) +
62                                            "; " + inlineCostStr(*OIC));
63     ORE.emit([&]() {
64       return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, Block)
65              << NV("Callee", Callee) << " will not be inlined into "
66              << NV("Caller", Caller) << ": "
67              << NV("Reason", Result.getFailureReason());
68     });
69   }
70 
71   void recordInliningWithCalleeDeletedImpl() override {
72     emitInlinedInto(ORE, DLoc, Block, *Callee, *Caller, *OIC);
73   }
74 
75   void recordInliningImpl() override {
76     emitInlinedInto(ORE, DLoc, Block, *Callee, *Caller, *OIC);
77   }
78 
79 private:
80   CallBase *const OriginalCB;
81   Optional<InlineCost> OIC;
82 };
83 
84 } // namespace
85 
86 std::unique_ptr<InlineAdvice> DefaultInlineAdvisor::getAdvice(CallBase &CB) {
87   Function &Caller = *CB.getCaller();
88   ProfileSummaryInfo *PSI =
89       FAM.getResult<ModuleAnalysisManagerFunctionProxy>(Caller)
90           .getCachedResult<ProfileSummaryAnalysis>(
91               *CB.getParent()->getParent()->getParent());
92 
93   auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(Caller);
94   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
95     return FAM.getResult<AssumptionAnalysis>(F);
96   };
97   auto GetBFI = [&](Function &F) -> BlockFrequencyInfo & {
98     return FAM.getResult<BlockFrequencyAnalysis>(F);
99   };
100   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
101     return FAM.getResult<TargetLibraryAnalysis>(F);
102   };
103 
104   auto GetInlineCost = [&](CallBase &CB) {
105     Function &Callee = *CB.getCalledFunction();
106     auto &CalleeTTI = FAM.getResult<TargetIRAnalysis>(Callee);
107     bool RemarksEnabled =
108         Callee.getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled(
109             DEBUG_TYPE);
110     return getInlineCost(CB, Params, CalleeTTI, GetAssumptionCache, GetTLI,
111                          GetBFI, PSI, RemarksEnabled ? &ORE : nullptr);
112   };
113   auto OIC = llvm::shouldInline(CB, GetInlineCost, ORE,
114                                 Params.EnableDeferral.hasValue() &&
115                                     Params.EnableDeferral.getValue());
116   return std::make_unique<DefaultInlineAdvice>(this, CB, OIC, ORE);
117 }
118 
119 InlineAdvice::InlineAdvice(InlineAdvisor *Advisor, CallBase &CB,
120                            OptimizationRemarkEmitter &ORE,
121                            bool IsInliningRecommended)
122     : Advisor(Advisor), Caller(CB.getCaller()), Callee(CB.getCalledFunction()),
123       DLoc(CB.getDebugLoc()), Block(CB.getParent()), ORE(ORE),
124       IsInliningRecommended(IsInliningRecommended) {}
125 
126 void InlineAdvisor::markFunctionAsDeleted(Function *F) {
127   assert((!DeletedFunctions.count(F)) &&
128          "Cannot put cause a function to become dead twice!");
129   DeletedFunctions.insert(F);
130 }
131 
132 void InlineAdvisor::freeDeletedFunctions() {
133   for (auto *F : DeletedFunctions)
134     delete F;
135   DeletedFunctions.clear();
136 }
137 
138 void InlineAdvice::recordInliningWithCalleeDeleted() {
139   markRecorded();
140   Advisor->markFunctionAsDeleted(Callee);
141   recordInliningWithCalleeDeletedImpl();
142 }
143 
144 AnalysisKey InlineAdvisorAnalysis::Key;
145 
146 bool InlineAdvisorAnalysis::Result::tryCreate(InlineParams Params,
147                                               InliningAdvisorMode Mode) {
148   auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
149   switch (Mode) {
150   case InliningAdvisorMode::Default:
151     Advisor.reset(new DefaultInlineAdvisor(FAM, Params));
152     break;
153   case InliningAdvisorMode::Development:
154     // To be added subsequently under conditional compilation.
155     break;
156   case InliningAdvisorMode::Release:
157     // To be added subsequently under conditional compilation.
158     break;
159   }
160   return !!Advisor;
161 }
162 
163 /// Return true if inlining of CB can block the caller from being
164 /// inlined which is proved to be more beneficial. \p IC is the
165 /// estimated inline cost associated with callsite \p CB.
166 /// \p TotalSecondaryCost will be set to the estimated cost of inlining the
167 /// caller if \p CB is suppressed for inlining.
168 static bool
169 shouldBeDeferred(Function *Caller, InlineCost IC, int &TotalSecondaryCost,
170                  function_ref<InlineCost(CallBase &CB)> GetInlineCost) {
171   // For now we only handle local or inline functions.
172   if (!Caller->hasLocalLinkage() && !Caller->hasLinkOnceODRLinkage())
173     return false;
174   // If the cost of inlining CB is non-positive, it is not going to prevent the
175   // caller from being inlined into its callers and hence we don't need to
176   // defer.
177   if (IC.getCost() <= 0)
178     return false;
179   // Try to detect the case where the current inlining candidate caller (call
180   // it B) is a static or linkonce-ODR function and is an inlining candidate
181   // elsewhere, and the current candidate callee (call it C) is large enough
182   // that inlining it into B would make B too big to inline later. In these
183   // circumstances it may be best not to inline C into B, but to inline B into
184   // its callers.
185   //
186   // This only applies to static and linkonce-ODR functions because those are
187   // expected to be available for inlining in the translation units where they
188   // are used. Thus we will always have the opportunity to make local inlining
189   // decisions. Importantly the linkonce-ODR linkage covers inline functions
190   // and templates in C++.
191   //
192   // FIXME: All of this logic should be sunk into getInlineCost. It relies on
193   // the internal implementation of the inline cost metrics rather than
194   // treating them as truly abstract units etc.
195   TotalSecondaryCost = 0;
196   // The candidate cost to be imposed upon the current function.
197   int CandidateCost = IC.getCost() - 1;
198   // If the caller has local linkage and can be inlined to all its callers, we
199   // can apply a huge negative bonus to TotalSecondaryCost.
200   bool ApplyLastCallBonus = Caller->hasLocalLinkage() && !Caller->hasOneUse();
201   // This bool tracks what happens if we DO inline C into B.
202   bool InliningPreventsSomeOuterInline = false;
203   unsigned NumCallerUsers = 0;
204   for (User *U : Caller->users()) {
205     CallBase *CS2 = dyn_cast<CallBase>(U);
206 
207     // If this isn't a call to Caller (it could be some other sort
208     // of reference) skip it.  Such references will prevent the caller
209     // from being removed.
210     if (!CS2 || CS2->getCalledFunction() != Caller) {
211       ApplyLastCallBonus = false;
212       continue;
213     }
214 
215     InlineCost IC2 = GetInlineCost(*CS2);
216     ++NumCallerCallersAnalyzed;
217     if (!IC2) {
218       ApplyLastCallBonus = false;
219       continue;
220     }
221     if (IC2.isAlways())
222       continue;
223 
224     // See if inlining of the original callsite would erase the cost delta of
225     // this callsite. We subtract off the penalty for the call instruction,
226     // which we would be deleting.
227     if (IC2.getCostDelta() <= CandidateCost) {
228       InliningPreventsSomeOuterInline = true;
229       TotalSecondaryCost += IC2.getCost();
230       NumCallerUsers++;
231     }
232   }
233 
234   if (!InliningPreventsSomeOuterInline)
235     return false;
236 
237   // If all outer calls to Caller would get inlined, the cost for the last
238   // one is set very low by getInlineCost, in anticipation that Caller will
239   // be removed entirely.  We did not account for this above unless there
240   // is only one caller of Caller.
241   if (ApplyLastCallBonus)
242     TotalSecondaryCost -= InlineConstants::LastCallToStaticBonus;
243 
244   // If InlineDeferralScale is negative, then ignore the cost of primary
245   // inlining -- IC.getCost() multiplied by the number of callers to Caller.
246   if (InlineDeferralScale < 0)
247     return TotalSecondaryCost < IC.getCost();
248 
249   int TotalCost = TotalSecondaryCost + IC.getCost() * NumCallerUsers;
250   int Allowance = IC.getCost() * InlineDeferralScale;
251   return TotalCost < Allowance;
252 }
253 
254 namespace llvm {
255 static std::basic_ostream<char> &operator<<(std::basic_ostream<char> &R,
256                                             const ore::NV &Arg) {
257   return R << Arg.Val;
258 }
259 
260 template <class RemarkT>
261 RemarkT &operator<<(RemarkT &&R, const InlineCost &IC) {
262   using namespace ore;
263   if (IC.isAlways()) {
264     R << "(cost=always)";
265   } else if (IC.isNever()) {
266     R << "(cost=never)";
267   } else {
268     R << "(cost=" << ore::NV("Cost", IC.getCost())
269       << ", threshold=" << ore::NV("Threshold", IC.getThreshold()) << ")";
270   }
271   if (const char *Reason = IC.getReason())
272     R << ": " << ore::NV("Reason", Reason);
273   return R;
274 }
275 } // namespace llvm
276 
277 std::string llvm::inlineCostStr(const InlineCost &IC) {
278   std::stringstream Remark;
279   Remark << IC;
280   return Remark.str();
281 }
282 
283 void llvm::setInlineRemark(CallBase &CB, StringRef Message) {
284   if (!InlineRemarkAttribute)
285     return;
286 
287   Attribute Attr = Attribute::get(CB.getContext(), "inline-remark", Message);
288   CB.addAttribute(AttributeList::FunctionIndex, Attr);
289 }
290 
291 /// Return the cost only if the inliner should attempt to inline at the given
292 /// CallSite. If we return the cost, we will emit an optimisation remark later
293 /// using that cost, so we won't do so from this function. Return None if
294 /// inlining should not be attempted.
295 Optional<InlineCost>
296 llvm::shouldInline(CallBase &CB,
297                    function_ref<InlineCost(CallBase &CB)> GetInlineCost,
298                    OptimizationRemarkEmitter &ORE, bool EnableDeferral) {
299   using namespace ore;
300 
301   InlineCost IC = GetInlineCost(CB);
302   Instruction *Call = &CB;
303   Function *Callee = CB.getCalledFunction();
304   Function *Caller = CB.getCaller();
305 
306   if (IC.isAlways()) {
307     LLVM_DEBUG(dbgs() << "    Inlining " << inlineCostStr(IC)
308                       << ", Call: " << CB << "\n");
309     return IC;
310   }
311 
312   if (!IC) {
313     LLVM_DEBUG(dbgs() << "    NOT Inlining " << inlineCostStr(IC)
314                       << ", Call: " << CB << "\n");
315     if (IC.isNever()) {
316       ORE.emit([&]() {
317         return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", Call)
318                << NV("Callee", Callee) << " not inlined into "
319                << NV("Caller", Caller) << " because it should never be inlined "
320                << IC;
321       });
322     } else {
323       ORE.emit([&]() {
324         return OptimizationRemarkMissed(DEBUG_TYPE, "TooCostly", Call)
325                << NV("Callee", Callee) << " not inlined into "
326                << NV("Caller", Caller) << " because too costly to inline "
327                << IC;
328       });
329     }
330     setInlineRemark(CB, inlineCostStr(IC));
331     return None;
332   }
333 
334   int TotalSecondaryCost = 0;
335   if (EnableDeferral &&
336       shouldBeDeferred(Caller, IC, TotalSecondaryCost, GetInlineCost)) {
337     LLVM_DEBUG(dbgs() << "    NOT Inlining: " << CB
338                       << " Cost = " << IC.getCost()
339                       << ", outer Cost = " << TotalSecondaryCost << '\n');
340     ORE.emit([&]() {
341       return OptimizationRemarkMissed(DEBUG_TYPE, "IncreaseCostInOtherContexts",
342                                       Call)
343              << "Not inlining. Cost of inlining " << NV("Callee", Callee)
344              << " increases the cost of inlining " << NV("Caller", Caller)
345              << " in other contexts";
346     });
347     setInlineRemark(CB, "deferred");
348     // IC does not bool() to false, so get an InlineCost that will.
349     // This will not be inspected to make an error message.
350     return None;
351   }
352 
353   LLVM_DEBUG(dbgs() << "    Inlining " << inlineCostStr(IC) << ", Call: " << CB
354                     << '\n');
355   return IC;
356 }
357 
358 void llvm::emitInlinedInto(OptimizationRemarkEmitter &ORE, DebugLoc DLoc,
359                            const BasicBlock *Block, const Function &Callee,
360                            const Function &Caller, const InlineCost &IC) {
361   ORE.emit([&]() {
362     bool AlwaysInline = IC.isAlways();
363     StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined";
364     return OptimizationRemark(DEBUG_TYPE, RemarkName, DLoc, Block)
365            << ore::NV("Callee", &Callee) << " inlined into "
366            << ore::NV("Caller", &Caller) << " with " << IC;
367   });
368 }
369