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, OIC.hasValue()), OriginalCB(&CB), OIC(OIC),
56         ORE(ORE), DLoc(CB.getDebugLoc()), Block(CB.getParent()) {}
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   OptimizationRemarkEmitter &ORE;
83 
84   // Capture the context of CB before inlining, as a successful inlining may
85   // change that context, and we want to report success or failure in the
86   // original context.
87   const DebugLoc DLoc;
88   const BasicBlock *const Block;
89 };
90 
91 } // namespace
92 
93 std::unique_ptr<InlineAdvice> DefaultInlineAdvisor::getAdvice(CallBase &CB) {
94   Function &Caller = *CB.getCaller();
95   ProfileSummaryInfo *PSI =
96       FAM.getResult<ModuleAnalysisManagerFunctionProxy>(Caller)
97           .getCachedResult<ProfileSummaryAnalysis>(
98               *CB.getParent()->getParent()->getParent());
99 
100   auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(Caller);
101   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
102     return FAM.getResult<AssumptionAnalysis>(F);
103   };
104   auto GetBFI = [&](Function &F) -> BlockFrequencyInfo & {
105     return FAM.getResult<BlockFrequencyAnalysis>(F);
106   };
107   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
108     return FAM.getResult<TargetLibraryAnalysis>(F);
109   };
110 
111   auto GetInlineCost = [&](CallBase &CB) {
112     Function &Callee = *CB.getCalledFunction();
113     auto &CalleeTTI = FAM.getResult<TargetIRAnalysis>(Callee);
114     bool RemarksEnabled =
115         Callee.getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled(
116             DEBUG_TYPE);
117     return getInlineCost(CB, Params, CalleeTTI, GetAssumptionCache, GetTLI,
118                          GetBFI, PSI, RemarksEnabled ? &ORE : nullptr);
119   };
120   auto OIC = llvm::shouldInline(CB, GetInlineCost, ORE,
121                                 Params.EnableDeferral.hasValue() &&
122                                     Params.EnableDeferral.getValue());
123   return std::make_unique<DefaultInlineAdvice>(this, CB, OIC, ORE);
124 }
125 
126 InlineAdvice::InlineAdvice(InlineAdvisor *Advisor, CallBase &CB,
127                            bool IsInliningRecommended)
128     : Advisor(Advisor), Caller(CB.getCaller()), Callee(CB.getCalledFunction()),
129       IsInliningRecommended(IsInliningRecommended) {}
130 
131 void InlineAdvisor::markFunctionAsDeleted(Function *F) {
132   assert((!DeletedFunctions.count(F)) &&
133          "Cannot put cause a function to become dead twice!");
134   DeletedFunctions.insert(F);
135 }
136 
137 void InlineAdvisor::freeDeletedFunctions() {
138   for (auto *F : DeletedFunctions)
139     delete F;
140   DeletedFunctions.clear();
141 }
142 
143 void InlineAdvice::recordInliningWithCalleeDeleted() {
144   markRecorded();
145   Advisor->markFunctionAsDeleted(Callee);
146   recordInliningWithCalleeDeletedImpl();
147 }
148 
149 AnalysisKey InlineAdvisorAnalysis::Key;
150 
151 bool InlineAdvisorAnalysis::Result::tryCreate(InlineParams Params,
152                                               InliningAdvisorMode Mode) {
153   auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
154   switch (Mode) {
155   case InliningAdvisorMode::Default:
156     Advisor.reset(new DefaultInlineAdvisor(FAM, Params));
157     break;
158   case InliningAdvisorMode::Development:
159     // To be added subsequently under conditional compilation.
160     break;
161   case InliningAdvisorMode::Release:
162     // To be added subsequently under conditional compilation.
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 void llvm::emitInlinedInto(OptimizationRemarkEmitter &ORE, DebugLoc DLoc,
364                            const BasicBlock *Block, const Function &Callee,
365                            const Function &Caller, const InlineCost &IC) {
366   ORE.emit([&]() {
367     bool AlwaysInline = IC.isAlways();
368     StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined";
369     return OptimizationRemark(DEBUG_TYPE, RemarkName, DLoc, Block)
370            << ore::NV("Callee", &Callee) << " inlined into "
371            << ore::NV("Caller", &Caller) << " with " << IC;
372   });
373 }
374