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