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