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