LLVM 24.0.0git
MLInlineAdvisor.cpp
Go to the documentation of this file.
1//===- MLInlineAdvisor.cpp - machine learned InlineAdvisor ----------------===//
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 the interface between the inliner and a learned model.
10// It delegates model evaluation to either the AOT compiled model (the
11// 'release' mode) or a runtime-loaded model (the 'development' case).
12//
13//===----------------------------------------------------------------------===//
15#include "AnalysisOptions.h"
32#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Module.h"
35#include "llvm/IR/PassManager.h"
37
38using namespace llvm;
39
40#if defined(LLVM_HAVE_TF_AOT_INLINERSIZEMODEL)
41// codegen-ed file
42#include "InlinerSizeModel.h" // NOLINT
43using CompiledModelType = llvm::InlinerSizeModel;
44#else
46#endif
47
49#include "llvm/Analysis/InlinerModels.h"
50
51enum class EmitCModelChoice {
53#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) CLASS_NAME,
54#include "llvm/Analysis/InlinerModels.def"
55};
56
58 "mlgo-model", llvm::cl::desc("Select the MLGO model to execute:"),
61 "Use standard heuristic")
62#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) \
63 , clEnumValN(EmitCModelChoice::CLASS_NAME, CLI_FLAG, \
64 "Use the " CLI_FLAG " MLGO model")
65#include "llvm/Analysis/InlinerModels.def"
66 ));
67
68static std::unique_ptr<MLModelRunner>
70 const std::vector<TensorSpec> &InputFeatures) {
71 switch (SelectedMLGOModel) {
73 return nullptr;
74#define MLGO_MODEL(CLASS_NAME, CLI_FLAG) \
75 case EmitCModelChoice::CLASS_NAME: \
76 return EmitCModelRunner<CLASS_NAME>::createAndEnsureValid(Ctx, \
77 InputFeatures);
78#include "llvm/Analysis/InlinerModels.def"
79 }
80 llvm_unreachable("Unknown MLGO model type!");
81}
82
83std::unique_ptr<InlineAdvisor>
85 std::function<bool(CallBase &)> GetDefaultAdvice) {
86 const AnalysisOptions &Opts = getAnalysisOptions(M);
88 Opts.inliner_interactive_channel_base, SelectedMLGOModel))
89 return nullptr;
90 auto RunnerFactory = [&](const std::vector<TensorSpec> &InputFeatures)
91 -> std::unique_ptr<MLModelRunner> {
93 M.getContext(), InputFeatures, DecisionName,
94 Opts.inliner_interactive_channel_base.str(), InlineDecisionSpec,
96 EmbeddedModelRunnerOptions().setModelSelector(
97 Opts.ml_inliner_model_selector));
98 };
99 return std::make_unique<MLInlineAdvisor>(M, MAM, RunnerFactory,
100 GetDefaultAdvice);
101}
102
103#define DEBUG_TYPE "inline-ml"
104
105const std::vector<TensorSpec> &MLInlineAdvisor::getInitialFeatureMap() {
106 // clang-format off
107static std::vector<TensorSpec> FeatureMap{
108#define POPULATE_NAMES(DTYPE, SHAPE, NAME, __) TensorSpec::createSpec<DTYPE>(#NAME, SHAPE),
109// InlineCost features - these must come first
111
112// Non-cost features
114#undef POPULATE_NAMES
115};
116 // clang-format on
117 return FeatureMap;
118}
119
120const char *const llvm::DecisionName = "inlining_decision";
123const char *const llvm::DefaultDecisionName = "inlining_default";
126const char *const llvm::RewardName = "delta_size";
127
129 if (auto *CS = dyn_cast<CallBase>(&I))
130 if (Function *Callee = CS->getCalledFunction()) {
131 if (!Callee->isDeclaration()) {
132 return CS;
133 }
134 }
135 return nullptr;
136}
137
140 std::function<
141 std::unique_ptr<MLModelRunner>(const std::vector<TensorSpec> &)>
142 GetModelRunner,
143 std::function<bool(CallBase &)> GetDefaultAdvice)
145 M, MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager()),
148 CG(MAM.getResult<LazyCallGraphAnalysis>(M)),
149 UseIR2Vec(MAM.getCachedResult<IR2VecVocabAnalysis>(M) != nullptr),
150 InitialIRSize(getModuleIRSize()), CurrentIRSize(InitialIRSize),
151 PSI(MAM.getResult<ProfileSummaryAnalysis>(M)) {
152 // Extract the 'call site height' feature - the position of a call site
153 // relative to the farthest statically reachable SCC node. We don't mutate
154 // this value while inlining happens. Empirically, this feature proved
155 // critical in behavioral cloning - i.e. training a model to mimic the manual
156 // heuristic's decisions - and, thus, equally important for training for
157 // improvement.
158 CallGraph CGraph(M);
159 for (auto I = scc_begin(&CGraph); !I.isAtEnd(); ++I) {
160 const std::vector<CallGraphNode *> &CGNodes = *I;
161 unsigned Level = 0;
162 for (auto *CGNode : CGNodes) {
163 Function *F = CGNode->getFunction();
164 if (!F || F->isDeclaration())
165 continue;
166 for (auto &I : instructions(F)) {
167 if (auto *CS = getInlinableCS(I)) {
168 auto *Called = CS->getCalledFunction();
169 auto Pos = FunctionLevels.find(&CG.get(*Called));
170 // In bottom up traversal, an inlinable callee is either in the
171 // same SCC, or to a function in a visited SCC. So not finding its
172 // level means we haven't visited it yet, meaning it's in this SCC.
173 if (Pos == FunctionLevels.end())
174 continue;
175 Level = std::max(Level, Pos->second + 1);
176 }
177 }
178 }
179 for (auto *CGNode : CGNodes) {
180 Function *F = CGNode->getFunction();
181 if (F && !F->isDeclaration())
182 FunctionLevels[&CG.get(*F)] = Level;
183 }
184 }
185 for (auto KVP : FunctionLevels) {
186 AllNodes.insert(KVP.first);
187 EdgeCount += getLocalCalls(KVP.first->getFunction());
188 }
189 NodeCount = AllNodes.size();
190
191 if (auto *IR2VecVocabResult = MAM.getCachedResult<IR2VecVocabAnalysis>(M)) {
192 if (!IR2VecVocabResult->isValid()) {
193 M.getContext().emitError("IR2VecVocabAnalysis is not valid");
194 return;
195 }
196 // Add the IR2Vec features to the feature map
197 auto IR2VecDim = IR2VecVocabResult->getDimension();
198 FeatureMap.push_back(
199 TensorSpec::createSpec<float>("callee_embedding", {IR2VecDim}));
200 FeatureMap.push_back(
201 TensorSpec::createSpec<float>("caller_embedding", {IR2VecDim}));
202 }
203 if (Opts.inliner_interactive_include_default)
205
206 ModelRunner = GetModelRunner(getFeatureMap());
207 if (!ModelRunner) {
208 M.getContext().emitError("Could not create model runner");
209 return;
210 }
211 ModelRunner->switchContext("");
212 ForceStop = Opts.ml_inliner_stop_immediately;
213}
214
216 return CG.lookup(F) ? FunctionLevels.at(CG.lookup(F)) : 0;
217}
218
220 if (!CurSCC || ForceStop)
221 return;
222 FPICache.clear();
223 // Function passes executed between InlinerPass runs may have changed the
224 // module-wide features.
225 // The cgscc pass manager rules are such that:
226 // - if a pass leads to merging SCCs, then the pipeline is restarted on the
227 // merged SCC
228 // - if a pass leads to splitting the SCC, then we continue with one of the
229 // splits
230 // This means that the NodesInLastSCC is a superset (not strict) of the nodes
231 // that subsequent passes would have processed
232 // - in addition, if new Nodes were created by a pass (e.g. CoroSplit),
233 // they'd be adjacent to Nodes in the last SCC. So we just need to check the
234 // boundary of Nodes in NodesInLastSCC for Nodes we haven't seen. We don't
235 // care about the nature of the Edge (call or ref). `FunctionLevels`-wise, we
236 // record them at the same level as the original node (this is a choice, may
237 // need revisiting).
238 // - nodes are only deleted at the end of a call graph walk where they are
239 // batch deleted, so we shouldn't see any dead nodes here.
240 while (!NodesInLastSCC.empty()) {
241 const auto *N = *NodesInLastSCC.begin();
242 assert(!N->isDead());
243 NodesInLastSCC.erase(N);
244 EdgeCount += getLocalCalls(N->getFunction());
245 const auto NLevel = FunctionLevels.at(N);
246 for (const auto &E : *(*N)) {
247 const auto *AdjNode = &E.getNode();
248 assert(!AdjNode->isDead() && !AdjNode->getFunction().isDeclaration());
249 auto I = AllNodes.insert(AdjNode);
250 // We've discovered a new function.
251 if (I.second) {
252 ++NodeCount;
253 NodesInLastSCC.insert(AdjNode);
254 FunctionLevels[AdjNode] = NLevel;
255 }
256 }
257 }
258
259 EdgeCount -= EdgesOfLastSeenNodes;
260 EdgesOfLastSeenNodes = 0;
261
262 // (Re)use NodesInLastSCC to remember the nodes in the SCC right now,
263 // in case the SCC is split before onPassExit and some nodes are split out
264 assert(NodesInLastSCC.empty());
265 for (const auto &N : *CurSCC)
266 NodesInLastSCC.insert(&N);
267}
268
270 // No need to keep this around - function passes will invalidate it.
271 if (!Opts.ml_advisor_keep_fpi_cache)
272 FPICache.clear();
273 if (!CurSCC || ForceStop)
274 return;
275 // Keep track of the nodes and edges we last saw. Then, in onPassEntry,
276 // we update the node count and edge count from the subset of these nodes that
277 // survived.
278 EdgesOfLastSeenNodes = 0;
279
280 // Check on nodes that were in SCC onPassEntry
281 for (const LazyCallGraph::Node *N : NodesInLastSCC) {
282 assert(!N->isDead());
283 EdgesOfLastSeenNodes += getLocalCalls(N->getFunction());
284 }
285
286 // Check on nodes that may have got added to SCC
287 for (const auto &N : *CurSCC) {
288 assert(!N.isDead());
289 auto I = NodesInLastSCC.insert(&N);
290 if (I.second)
291 EdgesOfLastSeenNodes += getLocalCalls(N.getFunction());
292 }
293 assert(NodeCount >= NodesInLastSCC.size());
294 assert(EdgeCount >= EdgesOfLastSeenNodes);
295}
296
300
301// Update the internal state of the advisor, and force invalidate feature
302// analysis. Currently, we maintain minimal (and very simple) global state - the
303// number of functions and the number of static calls. We also keep track of the
304// total IR size in this module, to stop misbehaving policies at a certain bloat
305// factor (-ml-advisor-size-increase-threshold)
307 bool CalleeWasDeleted) {
308 assert(!ForceStop);
309 Function *Caller = Advice.getCaller();
310 Function *Callee = Advice.getCallee();
311 // The caller features aren't valid anymore.
312 {
315 PA.abandon<LoopAnalysis>();
316 FAM.invalidate(*Caller, PA);
317 }
319 if (Caller == Callee) {
320 assert(!CalleeWasDeleted);
321 // We double-counted CallerAndCalleeEdges - since the caller and callee
322 // would be the same
323 assert(Advice.CallerAndCalleeEdges % 2 == 0);
324 CurrentIRSize += getIRSize(*Caller) - Advice.CallerIRSize;
325 EdgeCount += getCachedFPI(*Caller).DirectCallsToDefinedFunctions -
326 Advice.CallerAndCalleeEdges / 2;
327 // The NodeCount would stay the same.
328 } else {
329 int64_t IRSizeAfter =
330 getIRSize(*Caller) + (CalleeWasDeleted ? 0 : Advice.CalleeIRSize);
331 CurrentIRSize += IRSizeAfter - (Advice.CallerIRSize + Advice.CalleeIRSize);
332
333 // We can delta-update module-wide features. We know the inlining only
334 // changed the caller, and maybe the callee (by deleting the latter). Nodes
335 // are simple to update. For edges, we 'forget' the edges that the caller
336 // and callee used to have before inlining, and add back what they currently
337 // have together.
338 int64_t NewCallerAndCalleeEdges =
340
341 // A dead function's node is not actually removed from the call graph until
342 // the end of the call graph walk, but the node no longer belongs to any
343 // valid SCC.
344 if (CalleeWasDeleted) {
345 --NodeCount;
346 NodesInLastSCC.erase(CG.lookup(*Callee));
347 DeadFunctions.insert(Callee);
348 } else {
349 NewCallerAndCalleeEdges +=
351 }
352 EdgeCount += (NewCallerAndCalleeEdges - Advice.CallerAndCalleeEdges);
353 }
354 if (CurrentIRSize > Opts.ml_advisor_size_increase_threshold * InitialIRSize)
355 ForceStop = true;
356
357 assert(CurrentIRSize >= 0 && EdgeCount >= 0 && NodeCount >= 0);
358}
359
360int64_t MLInlineAdvisor::getModuleIRSize() const {
361 int64_t Ret = 0;
362 for (auto &F : M)
363 if (!F.isDeclaration())
364 Ret += getIRSize(F);
365 return Ret;
366}
367
369 auto InsertPair = FPICache.try_emplace(&F);
370 if (!InsertPair.second)
371 return InsertPair.first->second;
372 InsertPair.first->second = FAM.getResult<FunctionPropertiesAnalysis>(F);
373 return InsertPair.first->second;
374}
375
376std::unique_ptr<InlineAdvice> MLInlineAdvisor::getAdviceImpl(CallBase &CB) {
377 if (auto Skip = getSkipAdviceIfUnreachableCallsite(CB))
378 return Skip;
379
380 auto &Caller = *CB.getCaller();
381 auto &Callee = *CB.getCalledFunction();
382
383 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
384 return FAM.getResult<AssumptionAnalysis>(F);
385 };
386 auto &TIR = FAM.getResult<TargetIRAnalysis>(Caller);
387 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(Caller);
388
389 if (Opts.ml_inliner_skip_policy == SkipMLPolicyCriteria::IfCallerIsNotCold) {
390 if (!PSI.isFunctionEntryCold(&Caller)) {
391 // Return a MLInlineAdvice, despite delegating to the default advice,
392 // because we need to keep track of the internal state. This is different
393 // from the other instances where we return a "default" InlineAdvice,
394 // which happen at points we won't come back to the MLAdvisor for
395 // decisions requiring that state.
396 return ForceStop ? std::make_unique<InlineAdvice>(this, CB, ORE,
398 : std::make_unique<MLInlineAdvice>(this, CB, ORE,
399 GetDefaultAdvice(CB));
400 }
401 }
402 auto MandatoryKind = InlineAdvisor::getMandatoryKind(CB, FAM, ORE);
403 // If this is a "never inline" case, there won't be any changes to internal
404 // state we need to track, so we can just return the base InlineAdvice, which
405 // will do nothing interesting.
406 // Same thing if this is a recursive case.
407 if (MandatoryKind == InlineAdvisor::MandatoryInliningKind::Never ||
408 &Caller == &Callee)
409 return getMandatoryAdvice(CB, false);
410
411 bool Mandatory =
413
414 // If we need to stop, we won't want to track anymore any state changes, so
415 // we just return the base InlineAdvice, which acts as a noop.
416 if (ForceStop) {
417 ORE.emit([&] {
418 return OptimizationRemarkMissed(DEBUG_TYPE, "ForceStop", &CB)
419 << "Won't attempt inlining because module size grew too much.";
420 });
421 return std::make_unique<InlineAdvice>(this, CB, ORE, Mandatory);
422 }
423
424 int CostEstimate = 0;
425 if (!Mandatory) {
426 auto IsCallSiteInlinable =
427 llvm::getInliningCostEstimate(CB, TIR, GetAssumptionCache);
428 if (!IsCallSiteInlinable) {
429 // We can't inline this for correctness reasons, so return the base
430 // InlineAdvice, as we don't care about tracking any state changes (which
431 // won't happen).
432 return std::make_unique<InlineAdvice>(this, CB, ORE, false);
433 }
434 CostEstimate = *IsCallSiteInlinable;
435 }
436
437 const auto CostFeatures =
438 llvm::getInliningCostFeatures(CB, TIR, GetAssumptionCache);
439 if (!CostFeatures) {
440 return std::make_unique<InlineAdvice>(this, CB, ORE, false);
441 }
442
443 if (Mandatory)
444 return getMandatoryAdvice(CB, true);
445
446 auto NumCtantParams = 0;
447 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
448 NumCtantParams += (isa<Constant>(*I));
449 }
450
451 auto &CallerBefore = getCachedFPI(Caller);
452 auto &CalleeBefore = getCachedFPI(Callee);
453
454 *ModelRunner->getTensor<int64_t>(FeatureIndex::callee_basic_block_count) =
455 CalleeBefore.BasicBlockCount;
456 *ModelRunner->getTensor<int64_t>(FeatureIndex::callsite_height) =
458 *ModelRunner->getTensor<int64_t>(FeatureIndex::node_count) = NodeCount;
459 *ModelRunner->getTensor<int64_t>(FeatureIndex::nr_ctant_params) =
460 NumCtantParams;
461 *ModelRunner->getTensor<int64_t>(FeatureIndex::edge_count) = EdgeCount;
462 *ModelRunner->getTensor<int64_t>(FeatureIndex::caller_users) =
463 CallerBefore.Uses;
464 *ModelRunner->getTensor<int64_t>(
465 FeatureIndex::caller_conditionally_executed_blocks) =
466 CallerBefore.BlocksReachedFromConditionalInstruction;
467 *ModelRunner->getTensor<int64_t>(FeatureIndex::caller_basic_block_count) =
468 CallerBefore.BasicBlockCount;
469 *ModelRunner->getTensor<int64_t>(
470 FeatureIndex::callee_conditionally_executed_blocks) =
471 CalleeBefore.BlocksReachedFromConditionalInstruction;
472 *ModelRunner->getTensor<int64_t>(FeatureIndex::callee_users) =
473 CalleeBefore.Uses;
474 *ModelRunner->getTensor<int64_t>(FeatureIndex::cost_estimate) = CostEstimate;
475 *ModelRunner->getTensor<int64_t>(FeatureIndex::is_callee_avail_external) =
476 Callee.hasAvailableExternallyLinkage();
477 *ModelRunner->getTensor<int64_t>(FeatureIndex::is_caller_avail_external) =
478 Caller.hasAvailableExternallyLinkage();
479
480 if (UseIR2Vec) {
481 // Python side expects float embeddings. The IR2Vec embeddings are doubles
482 // as of now due to the restriction of fromJSON method used by the
483 // readVocabulary method in ir2vec::Embeddings.
484 auto setEmbedding = [&](const ir2vec::Embedding &Embedding,
485 FeatureIndex Index) {
486 llvm::transform(Embedding, ModelRunner->getTensor<float>(Index),
487 [](double Val) { return static_cast<float>(Val); });
488 };
489
490 setEmbedding(CalleeBefore.getFunctionEmbedding(),
492 setEmbedding(CallerBefore.getFunctionEmbedding(),
494 }
495
496 // Add the cost features
497 for (size_t I = 0;
499 *ModelRunner->getTensor<int64_t>(inlineCostFeatureToMlFeature(
500 static_cast<InlineCostFeatureIndex>(I))) = CostFeatures->at(I);
501 }
502 // This one would have been set up to be right at the end.
503 if (!Opts.inliner_interactive_channel_base.empty() &&
504 Opts.inliner_interactive_include_default)
505 *ModelRunner->getTensor<int64_t>(getFeatureMap().size() - 1) =
507 return getAdviceFromModel(CB, ORE);
508}
509
510std::unique_ptr<MLInlineAdvice>
513 return std::make_unique<MLInlineAdvice>(
514 this, CB, ORE, static_cast<bool>(ModelRunner->evaluate<int64_t>()));
515}
516
517std::unique_ptr<InlineAdvice>
518MLInlineAdvisor::getSkipAdviceIfUnreachableCallsite(CallBase &CB) {
519 if (!FAM.getResult<DominatorTreeAnalysis>(*CB.getCaller())
520 .isReachableFromEntry(CB.getParent()))
521 return std::make_unique<InlineAdvice>(this, CB, getCallerORE(CB), false);
522 return nullptr;
523}
524
525std::unique_ptr<InlineAdvice> MLInlineAdvisor::getMandatoryAdvice(CallBase &CB,
526 bool Advice) {
527 // Make sure we track inlinings in all cases - mandatory or not.
528 if (auto Skip = getSkipAdviceIfUnreachableCallsite(CB))
529 return Skip;
530 if (Advice && !ForceStop)
531 return getMandatoryAdviceImpl(CB);
532
533 // If this is a "never inline" case, there won't be any changes to internal
534 // state we need to track, so we can just return the base InlineAdvice, which
535 // will do nothing interesting.
536 // Same if we are forced to stop - we don't track anymore.
537 return std::make_unique<InlineAdvice>(this, CB, getCallerORE(CB), Advice);
538}
539
540std::unique_ptr<MLInlineAdvice>
542 return std::make_unique<MLInlineAdvice>(this, CB, getCallerORE(CB), true);
543}
544
545void MLInlineAdvisor::print(raw_ostream &OS) const {
546 OS << "[MLInlineAdvisor] Nodes: " << NodeCount << " Edges: " << EdgeCount
547 << " EdgesOfLastSeenNodes: " << EdgesOfLastSeenNodes << "\n";
548 OS << "[MLInlineAdvisor] FPI:\n";
549 for (auto I : FPICache) {
550 OS << I.first->getName() << ":\n";
551 I.second.print(OS);
552 OS << "\n";
553 }
554 OS << "\n";
555 OS << "[MLInlineAdvisor] FuncLevels:\n";
556 for (auto I : FunctionLevels)
557 OS << (DeadFunctions.contains(&I.first->getFunction())
558 ? "<deleted>"
559 : I.first->getFunction().getName())
560 << " : " << I.second << "\n";
561
562 OS << "\n";
563}
564
567 bool Recommendation)
568 : InlineAdvice(Advisor, CB, ORE, Recommendation),
569 CallerIRSize(Advisor->isForcedToStop() ? 0 : Advisor->getIRSize(*Caller)),
570 CalleeIRSize(Advisor->isForcedToStop() ? 0 : Advisor->getIRSize(*Callee)),
571 CallerAndCalleeEdges(Advisor->isForcedToStop()
572 ? 0
573 : (Advisor->getLocalCalls(*Caller) +
574 Advisor->getLocalCalls(*Callee))),
575 PreInlineCallerFPI(Advisor->getCachedFPI(*Caller)) {
576 if (Recommendation)
577 FPU.emplace(Advisor->getCachedFPI(*getCaller()), CB);
578}
579
580void MLInlineAdvice::reportContextForRemark(
582 using namespace ore;
583 OR << NV("Callee", Callee->getName());
584 for (size_t I = 0; I < getAdvisor()->getFeatureMap().size(); ++I)
585 OR << NV(getAdvisor()->getFeatureMap()[I].name(),
586 *getAdvisor()->getModelRunner().getTensor<int64_t>(I));
587 OR << NV("ShouldInline", isInliningRecommended());
588}
589
593
595 ORE.emit([&]() {
596 OptimizationRemark R(DEBUG_TYPE, "InliningSuccess", DLoc, Block);
597 reportContextForRemark(R);
598 return R;
599 });
600 getAdvisor()->onSuccessfulInlining(*this, /*CalleeWasDeleted*/ false);
601}
602
604 ORE.emit([&]() {
605 OptimizationRemark R(DEBUG_TYPE, "InliningSuccessWithCalleeDeleted", DLoc,
606 Block);
607 reportContextForRemark(R);
608 return R;
609 });
610 getAdvisor()->onSuccessfulInlining(*this, /*CalleeWasDeleted*/ true);
611}
612
614 const InlineResult &Result) {
615 getAdvisor()->getCachedFPI(*Caller) = PreInlineCallerFPI;
616 ORE.emit([&]() {
617 OptimizationRemarkMissed R(DEBUG_TYPE, "InliningAttemptedAndUnsuccessful",
618 DLoc, Block);
619 reportContextForRemark(R);
620 return R;
621 });
622}
624 assert(!FPU);
625 ORE.emit([&]() {
626 OptimizationRemarkMissed R(DEBUG_TYPE, "IniningNotAttempted", DLoc, Block);
627 reportContextForRemark(R);
628 return R;
629 });
630}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Expand Atomic instructions
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
@ Default
This file implements a model runner wrapping an EmitC compiled ML model.
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define INLINE_COST_FEATURE_ITERATOR(M)
#define INLINE_FEATURE_ITERATOR(M)
Implements a lazy call graph analysis and related passes for the new pass manager.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides helper functions for creating MLModelRunners and checking model validity in releas...
static std::unique_ptr< MLModelRunner > createEmitCModelRunner(LLVMContext &Ctx, const std::vector< TensorSpec > &InputFeatures)
#define MLGO_MODEL(CLASS_NAME, CLI_FLAG)
CallBase * getInlinableCS(Instruction &I)
NoopSavedModelImpl CompiledModelType
EmitCModelChoice
#define POPULATE_NAMES(DTYPE, SHAPE, NAME, __)
static llvm::cl::opt< EmitCModelChoice > SelectedMLGOModel("mlgo-model", llvm::cl::desc("Select the MLGO model to execute:"), llvm::cl::init(EmitCModelChoice::Default), llvm::cl::values(clEnumValN(EmitCModelChoice::Default, "default", "Use standard heuristic") #define MLGO_MODEL(CLASS_NAME, CLI_FLAG) \ \‍))
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
static const char * name
This pass exposes codegen information to IR-level passes.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
The basic data container for the call graph of a Module of IR.
Definition CallGraph.h:72
Common features for diagnostics dealing with optimization remarks that are used by both IR and MIR pa...
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
int64_t DirectCallsToDefinedFunctions
Number of direct calls made from this function to other functions defined in this module.
This analysis provides the vocabulary for IR2Vec.
Definition IR2Vec.h:636
Function *const Callee
Function *const Caller
Caller and Callee are pre-inlining.
const BasicBlock *const Block
OptimizationRemarkEmitter & ORE
InlineAdvisor *const Advisor
LLVM_ABI InlineAdvice(InlineAdvisor *Advisor, CallBase &CB, OptimizationRemarkEmitter &ORE, bool IsInliningRecommended)
const DebugLoc DLoc
bool isInliningRecommended() const
Get the inlining recommendation.
OptimizationRemarkEmitter & getCallerORE(CallBase &CB)
FunctionAnalysisManager & FAM
static MandatoryInliningKind getMandatoryKind(CallBase &CB, FunctionAnalysisManager &FAM, OptimizationRemarkEmitter &ORE)
InlineAdvisor(InlineAdvisor &&)=delete
InlineResult is basically true or false.
Definition InlineCost.h:184
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An analysis pass which computes the call graph for a module.
A node in the call graph.
An SCC of the call graph.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
InlineAdvice that tracks changes post inlining.
void updateCachedCallerFPI(FunctionAnalysisManager &FAM) const
const int64_t CallerIRSize
MLInlineAdvice(MLInlineAdvisor *Advisor, CallBase &CB, OptimizationRemarkEmitter &ORE, bool Recommendation)
const int64_t CalleeIRSize
void recordInliningImpl() override
Function * getCaller() const
const int64_t CallerAndCalleeEdges
void recordUnsuccessfulInliningImpl(const InlineResult &Result) override
Function * getCallee() const
void recordInliningWithCalleeDeletedImpl() override
void recordUnattemptedInliningImpl() override
const std::vector< TensorSpec > & getFeatureMap() const
const AnalysisOptions & Opts
std::unique_ptr< MLModelRunner > ModelRunner
FunctionPropertiesInfo & getCachedFPI(Function &) const
void onPassExit(LazyCallGraph::SCC *SCC) override
This must be called when the Inliner pass is exited, as function passes may be run subsequently.
void onSuccessfulInlining(const MLInlineAdvice &Advice, bool CalleeWasDeleted)
static const std::vector< TensorSpec > & getInitialFeatureMap()
virtual std::unique_ptr< MLInlineAdvice > getMandatoryAdviceImpl(CallBase &CB)
void onPassEntry(LazyCallGraph::SCC *SCC) override
This must be called when the Inliner pass is entered, to allow the InlineAdvisor update internal stat...
MLInlineAdvisor(Module &M, ModuleAnalysisManager &MAM, std::function< std::unique_ptr< MLModelRunner >(const std::vector< TensorSpec > &)> GetModelRunner, std::function< bool(CallBase &)> GetDefaultAdvice)
int64_t getLocalCalls(Function &F)
std::vector< TensorSpec > FeatureMap
virtual std::unique_ptr< MLInlineAdvice > getAdviceFromModel(CallBase &CB, OptimizationRemarkEmitter &ORE)
int64_t getIRSize(Function &F) const
std::function< bool(CallBase &)> GetDefaultAdvice
std::unique_ptr< InlineAdvice > getAdviceImpl(CallBase &CB) override
std::unique_ptr< InlineAdvice > getMandatoryAdvice(CallBase &CB, bool Advice) override
unsigned getInitialFunctionLevel(const Function &F) const
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A mock class satisfying the interface expected by ReleaseModeModelRunner for its TGen parameter.
The optimization diagnostic interface.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & abandon()
Mark an analysis as abandoned.
Definition Analysis.h:171
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis pass providing the TargetTransformInfo.
static TensorSpec createSpec(const std::string &Name, const std::vector< int64_t > &Shape, int Port=0)
Definition TensorSpec.h:65
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
This is an optimization pass for GlobalISel generic memory operations.
constexpr FeatureIndex inlineCostFeatureToMlFeature(InlineCostFeatureIndex Feature)
LLVM_ABI const char *const DefaultDecisionName
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
LLVM_ABI std::unique_ptr< InlineAdvisor > getReleaseModeAdvisor(Module &M, ModuleAnalysisManager &MAM, std::function< bool(CallBase &)> GetDefaultAdvice)
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
bool isReleaseModelValid(StringRef InteractiveChannelBaseName, const cl::opt< EnumType, ExternalStorage, ParserClass > &SelectedModel, EnumType DefaultModelVal=EnumType::Default)
Helper to check if a release-mode ML advisor has a valid model to execute.
Definition MLGOUtils.h:35
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
LLVM_ABI const TensorSpec DefaultDecisionSpec
std::unique_ptr< MLModelRunner > createReleaseModeModelRunner(LLVMContext &Ctx, const std::vector< TensorSpec > &InputFeatures, StringRef DecisionName, const std::string &InteractiveChannelBaseName, const TensorSpec &InteractiveDecisionSpec, CreateEmitCFunc &&CreateEmitCModelRunner, const EmbeddedModelRunnerOptions &Options={})
Helper to construct the appropriate MLModelRunner in release mode:
Definition MLGOUtils.h:61
LLVM_ABI const char *const DecisionName
static const std::vector< TensorSpec > InputFeatures
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI std::optional< int > getInliningCostEstimate(CallBase &Call, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, function_ref< const TargetLibraryInfo &(Function &)> GetTLI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Get the cost estimate ignoring thresholds.
LLVM_ABI const TensorSpec InlineDecisionSpec
LLVM_ABI const char *const RewardName
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI std::optional< InlineCostFeatures > getInliningCostFeatures(CallBase &Call, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, function_ref< const TargetLibraryInfo &(Function &)> GetTLI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Get the expanded cost features.
#define N
ReleaseModeModelRunner - production mode implementation of the MLModelRunner.
Embedding is a datatype that wraps std::vector<double>.
Definition IR2Vec.h:86