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 void DefaultInlineAdvice::recordUnsuccessfulInliningImpl(
52     const InlineResult &Result) {
53   using namespace ore;
54   llvm::setInlineRemark(*OriginalCB, std::string(Result.getFailureReason()) +
55                                          "; " + inlineCostStr(*OIC));
56   ORE.emit([&]() {
57     return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, Block)
58            << NV("Callee", Callee) << " will not be inlined into "
59            << NV("Caller", Caller) << ": "
60            << NV("Reason", Result.getFailureReason());
61   });
62 }
63 
64 void DefaultInlineAdvice::recordInliningWithCalleeDeletedImpl() {
65   if (EmitRemarks)
66     emitInlinedInto(ORE, DLoc, Block, *Callee, *Caller, *OIC);
67 }
68 
69 void DefaultInlineAdvice::recordInliningImpl() {
70   if (EmitRemarks)
71     emitInlinedInto(ORE, DLoc, Block, *Callee, *Caller, *OIC);
72 }
73 
74 llvm::Optional<llvm::InlineCost> static getDefaultInlineAdvice(
75     CallBase &CB, FunctionAnalysisManager &FAM, const InlineParams &Params) {
76   Function &Caller = *CB.getCaller();
77   ProfileSummaryInfo *PSI =
78       FAM.getResult<ModuleAnalysisManagerFunctionProxy>(Caller)
79           .getCachedResult<ProfileSummaryAnalysis>(
80               *CB.getParent()->getParent()->getParent());
81 
82   auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(Caller);
83   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
84     return FAM.getResult<AssumptionAnalysis>(F);
85   };
86   auto GetBFI = [&](Function &F) -> BlockFrequencyInfo & {
87     return FAM.getResult<BlockFrequencyAnalysis>(F);
88   };
89   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
90     return FAM.getResult<TargetLibraryAnalysis>(F);
91   };
92 
93   auto GetInlineCost = [&](CallBase &CB) {
94     Function &Callee = *CB.getCalledFunction();
95     auto &CalleeTTI = FAM.getResult<TargetIRAnalysis>(Callee);
96     bool RemarksEnabled =
97         Callee.getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled(
98             DEBUG_TYPE);
99     return getInlineCost(CB, Params, CalleeTTI, GetAssumptionCache, GetTLI,
100                          GetBFI, PSI, RemarksEnabled ? &ORE : nullptr);
101   };
102   return llvm::shouldInline(CB, GetInlineCost, ORE,
103                             Params.EnableDeferral.getValueOr(false));
104 }
105 
106 std::unique_ptr<InlineAdvice> DefaultInlineAdvisor::getAdvice(CallBase &CB) {
107   auto OIC = getDefaultInlineAdvice(CB, FAM, Params);
108   return std::make_unique<DefaultInlineAdvice>(
109       this, CB, OIC,
110       FAM.getResult<OptimizationRemarkEmitterAnalysis>(*CB.getCaller()));
111 }
112 
113 InlineAdvice::InlineAdvice(InlineAdvisor *Advisor, CallBase &CB,
114                            OptimizationRemarkEmitter &ORE,
115                            bool IsInliningRecommended)
116     : Advisor(Advisor), Caller(CB.getCaller()), Callee(CB.getCalledFunction()),
117       DLoc(CB.getDebugLoc()), Block(CB.getParent()), ORE(ORE),
118       IsInliningRecommended(IsInliningRecommended) {}
119 
120 void InlineAdvisor::markFunctionAsDeleted(Function *F) {
121   assert((!DeletedFunctions.count(F)) &&
122          "Cannot put cause a function to become dead twice!");
123   DeletedFunctions.insert(F);
124 }
125 
126 void InlineAdvisor::freeDeletedFunctions() {
127   for (auto *F : DeletedFunctions)
128     delete F;
129   DeletedFunctions.clear();
130 }
131 
132 void InlineAdvice::recordInliningWithCalleeDeleted() {
133   markRecorded();
134   Advisor->markFunctionAsDeleted(Callee);
135   recordInliningWithCalleeDeletedImpl();
136 }
137 
138 AnalysisKey InlineAdvisorAnalysis::Key;
139 
140 bool InlineAdvisorAnalysis::Result::tryCreate(InlineParams Params,
141                                               InliningAdvisorMode Mode) {
142   auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
143   switch (Mode) {
144   case InliningAdvisorMode::Default:
145     Advisor.reset(new DefaultInlineAdvisor(FAM, Params));
146     break;
147   case InliningAdvisorMode::MandatoryOnly:
148     Advisor.reset(new MandatoryInlineAdvisor(FAM));
149     break;
150   case InliningAdvisorMode::Development:
151 #ifdef LLVM_HAVE_TF_API
152     Advisor =
153         llvm::getDevelopmentModeAdvisor(M, MAM, [&FAM, Params](CallBase &CB) {
154           auto OIC = getDefaultInlineAdvice(CB, FAM, Params);
155           return OIC.hasValue();
156         });
157 #endif
158     break;
159   case InliningAdvisorMode::Release:
160 #ifdef LLVM_HAVE_TF_AOT
161     Advisor = llvm::getReleaseModeAdvisor(M, MAM);
162 #endif
163     break;
164   }
165   return !!Advisor;
166 }
167 
168 /// Return true if inlining of CB can block the caller from being
169 /// inlined which is proved to be more beneficial. \p IC is the
170 /// estimated inline cost associated with callsite \p CB.
171 /// \p TotalSecondaryCost will be set to the estimated cost of inlining the
172 /// caller if \p CB is suppressed for inlining.
173 static bool
174 shouldBeDeferred(Function *Caller, InlineCost IC, int &TotalSecondaryCost,
175                  function_ref<InlineCost(CallBase &CB)> GetInlineCost) {
176   // For now we only handle local or inline functions.
177   if (!Caller->hasLocalLinkage() && !Caller->hasLinkOnceODRLinkage())
178     return false;
179   // If the cost of inlining CB is non-positive, it is not going to prevent the
180   // caller from being inlined into its callers and hence we don't need to
181   // defer.
182   if (IC.getCost() <= 0)
183     return false;
184   // Try to detect the case where the current inlining candidate caller (call
185   // it B) is a static or linkonce-ODR function and is an inlining candidate
186   // elsewhere, and the current candidate callee (call it C) is large enough
187   // that inlining it into B would make B too big to inline later. In these
188   // circumstances it may be best not to inline C into B, but to inline B into
189   // its callers.
190   //
191   // This only applies to static and linkonce-ODR functions because those are
192   // expected to be available for inlining in the translation units where they
193   // are used. Thus we will always have the opportunity to make local inlining
194   // decisions. Importantly the linkonce-ODR linkage covers inline functions
195   // and templates in C++.
196   //
197   // FIXME: All of this logic should be sunk into getInlineCost. It relies on
198   // the internal implementation of the inline cost metrics rather than
199   // treating them as truly abstract units etc.
200   TotalSecondaryCost = 0;
201   // The candidate cost to be imposed upon the current function.
202   int CandidateCost = IC.getCost() - 1;
203   // If the caller has local linkage and can be inlined to all its callers, we
204   // can apply a huge negative bonus to TotalSecondaryCost.
205   bool ApplyLastCallBonus = Caller->hasLocalLinkage() && !Caller->hasOneUse();
206   // This bool tracks what happens if we DO inline C into B.
207   bool InliningPreventsSomeOuterInline = false;
208   unsigned NumCallerUsers = 0;
209   for (User *U : Caller->users()) {
210     CallBase *CS2 = dyn_cast<CallBase>(U);
211 
212     // If this isn't a call to Caller (it could be some other sort
213     // of reference) skip it.  Such references will prevent the caller
214     // from being removed.
215     if (!CS2 || CS2->getCalledFunction() != Caller) {
216       ApplyLastCallBonus = false;
217       continue;
218     }
219 
220     InlineCost IC2 = GetInlineCost(*CS2);
221     ++NumCallerCallersAnalyzed;
222     if (!IC2) {
223       ApplyLastCallBonus = false;
224       continue;
225     }
226     if (IC2.isAlways())
227       continue;
228 
229     // See if inlining of the original callsite would erase the cost delta of
230     // this callsite. We subtract off the penalty for the call instruction,
231     // which we would be deleting.
232     if (IC2.getCostDelta() <= CandidateCost) {
233       InliningPreventsSomeOuterInline = true;
234       TotalSecondaryCost += IC2.getCost();
235       NumCallerUsers++;
236     }
237   }
238 
239   if (!InliningPreventsSomeOuterInline)
240     return false;
241 
242   // If all outer calls to Caller would get inlined, the cost for the last
243   // one is set very low by getInlineCost, in anticipation that Caller will
244   // be removed entirely.  We did not account for this above unless there
245   // is only one caller of Caller.
246   if (ApplyLastCallBonus)
247     TotalSecondaryCost -= InlineConstants::LastCallToStaticBonus;
248 
249   // If InlineDeferralScale is negative, then ignore the cost of primary
250   // inlining -- IC.getCost() multiplied by the number of callers to Caller.
251   if (InlineDeferralScale < 0)
252     return TotalSecondaryCost < IC.getCost();
253 
254   int TotalCost = TotalSecondaryCost + IC.getCost() * NumCallerUsers;
255   int Allowance = IC.getCost() * InlineDeferralScale;
256   return TotalCost < Allowance;
257 }
258 
259 namespace llvm {
260 static std::basic_ostream<char> &operator<<(std::basic_ostream<char> &R,
261                                             const ore::NV &Arg) {
262   return R << Arg.Val;
263 }
264 
265 template <class RemarkT>
266 RemarkT &operator<<(RemarkT &&R, const InlineCost &IC) {
267   using namespace ore;
268   if (IC.isAlways()) {
269     R << "(cost=always)";
270   } else if (IC.isNever()) {
271     R << "(cost=never)";
272   } else {
273     R << "(cost=" << ore::NV("Cost", IC.getCost())
274       << ", threshold=" << ore::NV("Threshold", IC.getThreshold()) << ")";
275   }
276   if (const char *Reason = IC.getReason())
277     R << ": " << ore::NV("Reason", Reason);
278   return R;
279 }
280 } // namespace llvm
281 
282 std::string llvm::inlineCostStr(const InlineCost &IC) {
283   std::stringstream Remark;
284   Remark << IC;
285   return Remark.str();
286 }
287 
288 void llvm::setInlineRemark(CallBase &CB, StringRef Message) {
289   if (!InlineRemarkAttribute)
290     return;
291 
292   Attribute Attr = Attribute::get(CB.getContext(), "inline-remark", Message);
293   CB.addAttribute(AttributeList::FunctionIndex, Attr);
294 }
295 
296 /// Return the cost only if the inliner should attempt to inline at the given
297 /// CallSite. If we return the cost, we will emit an optimisation remark later
298 /// using that cost, so we won't do so from this function. Return None if
299 /// inlining should not be attempted.
300 Optional<InlineCost>
301 llvm::shouldInline(CallBase &CB,
302                    function_ref<InlineCost(CallBase &CB)> GetInlineCost,
303                    OptimizationRemarkEmitter &ORE, bool EnableDeferral) {
304   using namespace ore;
305 
306   InlineCost IC = GetInlineCost(CB);
307   Instruction *Call = &CB;
308   Function *Callee = CB.getCalledFunction();
309   Function *Caller = CB.getCaller();
310 
311   if (IC.isAlways()) {
312     LLVM_DEBUG(dbgs() << "    Inlining " << inlineCostStr(IC)
313                       << ", Call: " << CB << "\n");
314     return IC;
315   }
316 
317   if (!IC) {
318     LLVM_DEBUG(dbgs() << "    NOT Inlining " << inlineCostStr(IC)
319                       << ", Call: " << CB << "\n");
320     if (IC.isNever()) {
321       ORE.emit([&]() {
322         return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", Call)
323                << NV("Callee", Callee) << " not inlined into "
324                << NV("Caller", Caller) << " because it should never be inlined "
325                << IC;
326       });
327     } else {
328       ORE.emit([&]() {
329         return OptimizationRemarkMissed(DEBUG_TYPE, "TooCostly", Call)
330                << NV("Callee", Callee) << " not inlined into "
331                << NV("Caller", Caller) << " because too costly to inline "
332                << IC;
333       });
334     }
335     setInlineRemark(CB, inlineCostStr(IC));
336     return None;
337   }
338 
339   int TotalSecondaryCost = 0;
340   if (EnableDeferral &&
341       shouldBeDeferred(Caller, IC, TotalSecondaryCost, GetInlineCost)) {
342     LLVM_DEBUG(dbgs() << "    NOT Inlining: " << CB
343                       << " Cost = " << IC.getCost()
344                       << ", outer Cost = " << TotalSecondaryCost << '\n');
345     ORE.emit([&]() {
346       return OptimizationRemarkMissed(DEBUG_TYPE, "IncreaseCostInOtherContexts",
347                                       Call)
348              << "Not inlining. Cost of inlining " << NV("Callee", Callee)
349              << " increases the cost of inlining " << NV("Caller", Caller)
350              << " in other contexts";
351     });
352     setInlineRemark(CB, "deferred");
353     // IC does not bool() to false, so get an InlineCost that will.
354     // This will not be inspected to make an error message.
355     return None;
356   }
357 
358   LLVM_DEBUG(dbgs() << "    Inlining " << inlineCostStr(IC) << ", Call: " << CB
359                     << '\n');
360   return IC;
361 }
362 
363 std::string llvm::getCallSiteLocation(DebugLoc DLoc) {
364   std::ostringstream CallSiteLoc;
365   bool First = true;
366   for (DILocation *DIL = DLoc.get(); DIL; DIL = DIL->getInlinedAt()) {
367     if (!First)
368       CallSiteLoc << " @ ";
369     // Note that negative line offset is actually possible, but we use
370     // unsigned int to match line offset representation in remarks so
371     // it's directly consumable by relay advisor.
372     uint32_t Offset =
373         DIL->getLine() - DIL->getScope()->getSubprogram()->getLine();
374     uint32_t Discriminator = DIL->getBaseDiscriminator();
375     StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
376     if (Name.empty())
377       Name = DIL->getScope()->getSubprogram()->getName();
378     CallSiteLoc << Name.str() << ":" << llvm::utostr(Offset) << ":"
379                 << llvm::utostr(DIL->getColumn());
380     if (Discriminator)
381       CallSiteLoc << "." << llvm::utostr(Discriminator);
382     First = false;
383   }
384 
385   return CallSiteLoc.str();
386 }
387 
388 void llvm::addLocationToRemarks(OptimizationRemark &Remark, DebugLoc DLoc) {
389   if (!DLoc.get()) {
390     return;
391   }
392 
393   bool First = true;
394   Remark << " at callsite ";
395   for (DILocation *DIL = DLoc.get(); DIL; DIL = DIL->getInlinedAt()) {
396     if (!First)
397       Remark << " @ ";
398     unsigned int Offset = DIL->getLine();
399     Offset -= DIL->getScope()->getSubprogram()->getLine();
400     unsigned int Discriminator = DIL->getBaseDiscriminator();
401     StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
402     if (Name.empty())
403       Name = DIL->getScope()->getSubprogram()->getName();
404     Remark << Name << ":" << ore::NV("Line", Offset) << ":"
405            << ore::NV("Column", DIL->getColumn());
406     if (Discriminator)
407       Remark << "." << ore::NV("Disc", Discriminator);
408     First = false;
409   }
410 
411   Remark << ";";
412 }
413 
414 void llvm::emitInlinedInto(OptimizationRemarkEmitter &ORE, DebugLoc DLoc,
415                            const BasicBlock *Block, const Function &Callee,
416                            const Function &Caller, const InlineCost &IC,
417                            bool ForProfileContext, const char *PassName) {
418   ORE.emit([&]() {
419     bool AlwaysInline = IC.isAlways();
420     StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined";
421     OptimizationRemark Remark(PassName ? PassName : DEBUG_TYPE, RemarkName,
422                               DLoc, Block);
423     Remark << ore::NV("Callee", &Callee) << " inlined into ";
424     Remark << ore::NV("Caller", &Caller);
425     if (ForProfileContext)
426       Remark << " to match profiling context";
427     Remark << " with " << IC;
428     addLocationToRemarks(Remark, DLoc);
429     return Remark;
430   });
431 }
432 
433 std::unique_ptr<InlineAdvice> MandatoryInlineAdvisor::getAdvice(CallBase &CB) {
434   auto &Caller = *CB.getCaller();
435   auto &Callee = *CB.getCalledFunction();
436   auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(Caller);
437 
438   bool Advice = MandatoryInliningKind::Always ==
439                     MandatoryInlineAdvisor::getMandatoryKind(CB, FAM, ORE) &&
440                 &Caller != &Callee;
441   return std::make_unique<InlineAdvice>(this, CB, ORE, Advice);
442 }
443 
444 MandatoryInlineAdvisor::MandatoryInliningKind
445 MandatoryInlineAdvisor::getMandatoryKind(CallBase &CB,
446                                          FunctionAnalysisManager &FAM,
447                                          OptimizationRemarkEmitter &ORE) {
448   auto &Callee = *CB.getCalledFunction();
449 
450   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
451     return FAM.getResult<TargetLibraryAnalysis>(F);
452   };
453 
454   auto &TIR = FAM.getResult<TargetIRAnalysis>(Callee);
455 
456   auto TrivialDecision =
457       llvm::getAttributeBasedInliningDecision(CB, &Callee, TIR, GetTLI);
458 
459   if (TrivialDecision.hasValue()) {
460     if (TrivialDecision->isSuccess())
461       return MandatoryInliningKind::Always;
462     else
463       return MandatoryInliningKind::Never;
464   }
465   return MandatoryInliningKind::NotMandatory;
466 }
467