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 //===----------------------------------------------------------------------===// 14 #include "llvm/Analysis/MLInlineAdvisor.h" 15 #include "llvm/ADT/SCCIterator.h" 16 #include "llvm/Analysis/AssumptionCache.h" 17 #include "llvm/Analysis/CallGraph.h" 18 #include "llvm/Analysis/FunctionPropertiesAnalysis.h" 19 #include "llvm/Analysis/InlineCost.h" 20 #include "llvm/Analysis/InlineModelFeatureMaps.h" 21 #include "llvm/Analysis/LazyCallGraph.h" 22 #include "llvm/Analysis/LoopInfo.h" 23 #include "llvm/Analysis/MLModelRunner.h" 24 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 25 #include "llvm/Analysis/TargetTransformInfo.h" 26 #include "llvm/IR/Dominators.h" 27 #include "llvm/IR/InstIterator.h" 28 #include "llvm/IR/PassManager.h" 29 #include "llvm/Support/CommandLine.h" 30 31 using namespace llvm; 32 33 #if defined(LLVM_HAVE_TF_AOT_INLINERSIZEMODEL) 34 #include "llvm/Analysis/ReleaseModeModelRunner.h" 35 // codegen-ed file 36 #include "InlinerSizeModel.h" // NOLINT 37 38 std::unique_ptr<InlineAdvisor> 39 llvm::getReleaseModeAdvisor(Module &M, ModuleAnalysisManager &MAM) { 40 auto AOTRunner = 41 std::make_unique<ReleaseModeModelRunner<llvm::InlinerSizeModel>>( 42 M.getContext(), FeatureMap, DecisionName); 43 return std::make_unique<MLInlineAdvisor>(M, MAM, std::move(AOTRunner)); 44 } 45 #endif 46 47 #define DEBUG_TYPE "inline-ml" 48 49 static cl::opt<float> SizeIncreaseThreshold( 50 "ml-advisor-size-increase-threshold", cl::Hidden, 51 cl::desc("Maximum factor by which expected native size may increase before " 52 "blocking any further inlining."), 53 cl::init(2.0)); 54 55 static cl::opt<bool> KeepFPICache( 56 "ml-advisor-keep-fpi-cache", cl::Hidden, 57 cl::desc( 58 "For test - keep the ML Inline advisor's FunctionPropertiesInfo cache"), 59 cl::init(false)); 60 61 // clang-format off 62 const std::array<TensorSpec, NumberOfFeatures> llvm::FeatureMap{ 63 #define POPULATE_NAMES(_, NAME) TensorSpec::createSpec<int64_t>(NAME, {1} ), 64 // InlineCost features - these must come first 65 INLINE_COST_FEATURE_ITERATOR(POPULATE_NAMES) 66 #undef POPULATE_NAMES 67 68 // Non-cost features 69 #define POPULATE_NAMES(_, NAME, __) TensorSpec::createSpec<int64_t>(NAME, {1} ), 70 INLINE_FEATURE_ITERATOR(POPULATE_NAMES) 71 #undef POPULATE_NAMES 72 }; 73 // clang-format on 74 75 const char *const llvm::DecisionName = "inlining_decision"; 76 const char *const llvm::DefaultDecisionName = "inlining_default"; 77 const char *const llvm::RewardName = "delta_size"; 78 79 CallBase *getInlinableCS(Instruction &I) { 80 if (auto *CS = dyn_cast<CallBase>(&I)) 81 if (Function *Callee = CS->getCalledFunction()) { 82 if (!Callee->isDeclaration()) { 83 return CS; 84 } 85 } 86 return nullptr; 87 } 88 89 MLInlineAdvisor::MLInlineAdvisor(Module &M, ModuleAnalysisManager &MAM, 90 std::unique_ptr<MLModelRunner> Runner) 91 : InlineAdvisor( 92 M, MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager()), 93 ModelRunner(std::move(Runner)), 94 CG(MAM.getResult<LazyCallGraphAnalysis>(M)), 95 InitialIRSize(getModuleIRSize()), CurrentIRSize(InitialIRSize) { 96 assert(ModelRunner); 97 98 // Extract the 'call site height' feature - the position of a call site 99 // relative to the farthest statically reachable SCC node. We don't mutate 100 // this value while inlining happens. Empirically, this feature proved 101 // critical in behavioral cloning - i.e. training a model to mimic the manual 102 // heuristic's decisions - and, thus, equally important for training for 103 // improvement. 104 CallGraph CGraph(M); 105 for (auto I = scc_begin(&CGraph); !I.isAtEnd(); ++I) { 106 const std::vector<CallGraphNode *> &CGNodes = *I; 107 unsigned Level = 0; 108 for (auto *CGNode : CGNodes) { 109 Function *F = CGNode->getFunction(); 110 if (!F || F->isDeclaration()) 111 continue; 112 for (auto &I : instructions(F)) { 113 if (auto *CS = getInlinableCS(I)) { 114 auto *Called = CS->getCalledFunction(); 115 auto Pos = FunctionLevels.find(&CG.get(*Called)); 116 // In bottom up traversal, an inlinable callee is either in the 117 // same SCC, or to a function in a visited SCC. So not finding its 118 // level means we haven't visited it yet, meaning it's in this SCC. 119 if (Pos == FunctionLevels.end()) 120 continue; 121 Level = std::max(Level, Pos->second + 1); 122 } 123 } 124 } 125 for (auto *CGNode : CGNodes) { 126 Function *F = CGNode->getFunction(); 127 if (F && !F->isDeclaration()) 128 FunctionLevels[&CG.get(*F)] = Level; 129 } 130 } 131 for (auto KVP : FunctionLevels) { 132 AllNodes.insert(KVP.first); 133 EdgeCount += getLocalCalls(KVP.first->getFunction()); 134 } 135 NodeCount = AllNodes.size(); 136 } 137 138 unsigned MLInlineAdvisor::getInitialFunctionLevel(const Function &F) const { 139 return CG.lookup(F) ? FunctionLevels.at(CG.lookup(F)) : 0; 140 } 141 142 void MLInlineAdvisor::onPassEntry(LazyCallGraph::SCC *LastSCC) { 143 if (!LastSCC || ForceStop) 144 return; 145 FPICache.clear(); 146 // Function passes executed between InlinerPass runs may have changed the 147 // module-wide features. 148 // The cgscc pass manager rules are such that: 149 // - if a pass leads to merging SCCs, then the pipeline is restarted on the 150 // merged SCC 151 // - if a pass leads to splitting the SCC, then we continue with one of the 152 // splits 153 // This means that the NodesInLastSCC is a superset (not strict) of the nodes 154 // that subsequent passes would have processed 155 // - in addition, if new Nodes were created by a pass (e.g. CoroSplit), 156 // they'd be adjacent to Nodes in the last SCC. So we just need to check the 157 // boundary of Nodes in NodesInLastSCC for Nodes we haven't seen. We don't 158 // care about the nature of the Edge (call or ref). 159 NodeCount -= static_cast<int64_t>(NodesInLastSCC.size()); 160 while (!NodesInLastSCC.empty()) { 161 const auto *N = *NodesInLastSCC.begin(); 162 NodesInLastSCC.erase(N); 163 // The Function wrapped by N could have been deleted since we last saw it. 164 if (N->isDead()) { 165 assert(!N->getFunction().isDeclaration()); 166 continue; 167 } 168 ++NodeCount; 169 EdgeCount += getLocalCalls(N->getFunction()); 170 for (const auto &E : *(*N)) { 171 const auto *AdjNode = &E.getNode(); 172 assert(!AdjNode->isDead() && !AdjNode->getFunction().isDeclaration()); 173 auto I = AllNodes.insert(AdjNode); 174 if (I.second) 175 NodesInLastSCC.insert(AdjNode); 176 } 177 } 178 179 EdgeCount -= EdgesOfLastSeenNodes; 180 EdgesOfLastSeenNodes = 0; 181 182 // (Re)use NodesInLastSCC to remember the nodes in the SCC right now, 183 // in case the SCC is split before onPassExit and some nodes are split out 184 assert(NodesInLastSCC.empty()); 185 for (const auto &N : *LastSCC) 186 NodesInLastSCC.insert(&N); 187 } 188 189 void MLInlineAdvisor::onPassExit(LazyCallGraph::SCC *LastSCC) { 190 // No need to keep this around - function passes will invalidate it. 191 if (!KeepFPICache) 192 FPICache.clear(); 193 if (!LastSCC || ForceStop) 194 return; 195 // Keep track of the nodes and edges we last saw. Then, in onPassEntry, 196 // we update the node count and edge count from the subset of these nodes that 197 // survived. 198 EdgesOfLastSeenNodes = 0; 199 200 // Check on nodes that were in SCC onPassEntry 201 for (auto I = NodesInLastSCC.begin(); I != NodesInLastSCC.end();) { 202 if ((*I)->isDead()) 203 NodesInLastSCC.erase(*I++); 204 else 205 EdgesOfLastSeenNodes += getLocalCalls((*I++)->getFunction()); 206 } 207 208 // Check on nodes that may have got added to SCC 209 for (const auto &N : *LastSCC) { 210 assert(!N.isDead()); 211 auto I = NodesInLastSCC.insert(&N); 212 if (I.second) 213 EdgesOfLastSeenNodes += getLocalCalls(N.getFunction()); 214 } 215 assert(NodeCount >= NodesInLastSCC.size()); 216 assert(EdgeCount >= EdgesOfLastSeenNodes); 217 } 218 219 int64_t MLInlineAdvisor::getLocalCalls(Function &F) { 220 return getCachedFPI(F).DirectCallsToDefinedFunctions; 221 } 222 223 // Update the internal state of the advisor, and force invalidate feature 224 // analysis. Currently, we maintain minimal (and very simple) global state - the 225 // number of functions and the number of static calls. We also keep track of the 226 // total IR size in this module, to stop misbehaving policies at a certain bloat 227 // factor (SizeIncreaseThreshold) 228 void MLInlineAdvisor::onSuccessfulInlining(const MLInlineAdvice &Advice, 229 bool CalleeWasDeleted) { 230 assert(!ForceStop); 231 Function *Caller = Advice.getCaller(); 232 Function *Callee = Advice.getCallee(); 233 // The caller features aren't valid anymore. 234 { 235 PreservedAnalyses PA = PreservedAnalyses::none(); 236 FAM.invalidate(*Caller, PA); 237 } 238 Advice.updateCachedCallerFPI(FAM); 239 int64_t IRSizeAfter = 240 getIRSize(*Caller) + (CalleeWasDeleted ? 0 : Advice.CalleeIRSize); 241 CurrentIRSize += IRSizeAfter - (Advice.CallerIRSize + Advice.CalleeIRSize); 242 if (CurrentIRSize > SizeIncreaseThreshold * InitialIRSize) 243 ForceStop = true; 244 245 // We can delta-update module-wide features. We know the inlining only changed 246 // the caller, and maybe the callee (by deleting the latter). 247 // Nodes are simple to update. 248 // For edges, we 'forget' the edges that the caller and callee used to have 249 // before inlining, and add back what they currently have together. 250 int64_t NewCallerAndCalleeEdges = 251 getCachedFPI(*Caller).DirectCallsToDefinedFunctions; 252 253 if (CalleeWasDeleted) 254 --NodeCount; 255 else 256 NewCallerAndCalleeEdges += 257 getCachedFPI(*Callee).DirectCallsToDefinedFunctions; 258 EdgeCount += (NewCallerAndCalleeEdges - Advice.CallerAndCalleeEdges); 259 assert(CurrentIRSize >= 0 && EdgeCount >= 0 && NodeCount >= 0); 260 } 261 262 int64_t MLInlineAdvisor::getModuleIRSize() const { 263 int64_t Ret = 0; 264 for (auto &F : M) 265 if (!F.isDeclaration()) 266 Ret += getIRSize(F); 267 return Ret; 268 } 269 270 FunctionPropertiesInfo &MLInlineAdvisor::getCachedFPI(Function &F) const { 271 auto InsertPair = 272 FPICache.insert(std::make_pair(&F, FunctionPropertiesInfo())); 273 if (!InsertPair.second) 274 return InsertPair.first->second; 275 InsertPair.first->second = FAM.getResult<FunctionPropertiesAnalysis>(F); 276 return InsertPair.first->second; 277 } 278 279 std::unique_ptr<InlineAdvice> MLInlineAdvisor::getAdviceImpl(CallBase &CB) { 280 auto &Caller = *CB.getCaller(); 281 auto &Callee = *CB.getCalledFunction(); 282 283 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & { 284 return FAM.getResult<AssumptionAnalysis>(F); 285 }; 286 auto &TIR = FAM.getResult<TargetIRAnalysis>(Callee); 287 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(Caller); 288 289 auto MandatoryKind = InlineAdvisor::getMandatoryKind(CB, FAM, ORE); 290 // If this is a "never inline" case, there won't be any changes to internal 291 // state we need to track, so we can just return the base InlineAdvice, which 292 // will do nothing interesting. 293 // Same thing if this is a recursive case. 294 if (MandatoryKind == InlineAdvisor::MandatoryInliningKind::Never || 295 &Caller == &Callee) 296 return getMandatoryAdvice(CB, false); 297 298 bool Mandatory = 299 MandatoryKind == InlineAdvisor::MandatoryInliningKind::Always; 300 301 // If we need to stop, we won't want to track anymore any state changes, so 302 // we just return the base InlineAdvice, which acts as a noop. 303 if (ForceStop) { 304 ORE.emit([&] { 305 return OptimizationRemarkMissed(DEBUG_TYPE, "ForceStop", &CB) 306 << "Won't attempt inlining because module size grew too much."; 307 }); 308 return std::make_unique<InlineAdvice>(this, CB, ORE, Mandatory); 309 } 310 311 int CostEstimate = 0; 312 if (!Mandatory) { 313 auto IsCallSiteInlinable = 314 llvm::getInliningCostEstimate(CB, TIR, GetAssumptionCache); 315 if (!IsCallSiteInlinable) { 316 // We can't inline this for correctness reasons, so return the base 317 // InlineAdvice, as we don't care about tracking any state changes (which 318 // won't happen). 319 return std::make_unique<InlineAdvice>(this, CB, ORE, false); 320 } 321 CostEstimate = *IsCallSiteInlinable; 322 } 323 324 const auto CostFeatures = 325 llvm::getInliningCostFeatures(CB, TIR, GetAssumptionCache); 326 if (!CostFeatures) { 327 return std::make_unique<InlineAdvice>(this, CB, ORE, false); 328 } 329 330 if (Mandatory) 331 return getMandatoryAdvice(CB, true); 332 333 auto NrCtantParams = 0; 334 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 335 NrCtantParams += (isa<Constant>(*I)); 336 } 337 338 auto &CallerBefore = getCachedFPI(Caller); 339 auto &CalleeBefore = getCachedFPI(Callee); 340 341 *ModelRunner->getTensor<int64_t>(FeatureIndex::CalleeBasicBlockCount) = 342 CalleeBefore.BasicBlockCount; 343 *ModelRunner->getTensor<int64_t>(FeatureIndex::CallSiteHeight) = 344 getInitialFunctionLevel(Caller); 345 *ModelRunner->getTensor<int64_t>(FeatureIndex::NodeCount) = NodeCount; 346 *ModelRunner->getTensor<int64_t>(FeatureIndex::NrCtantParams) = NrCtantParams; 347 *ModelRunner->getTensor<int64_t>(FeatureIndex::EdgeCount) = EdgeCount; 348 *ModelRunner->getTensor<int64_t>(FeatureIndex::CallerUsers) = 349 CallerBefore.Uses; 350 *ModelRunner->getTensor<int64_t>( 351 FeatureIndex::CallerConditionallyExecutedBlocks) = 352 CallerBefore.BlocksReachedFromConditionalInstruction; 353 *ModelRunner->getTensor<int64_t>(FeatureIndex::CallerBasicBlockCount) = 354 CallerBefore.BasicBlockCount; 355 *ModelRunner->getTensor<int64_t>( 356 FeatureIndex::CalleeConditionallyExecutedBlocks) = 357 CalleeBefore.BlocksReachedFromConditionalInstruction; 358 *ModelRunner->getTensor<int64_t>(FeatureIndex::CalleeUsers) = 359 CalleeBefore.Uses; 360 *ModelRunner->getTensor<int64_t>(FeatureIndex::CostEstimate) = CostEstimate; 361 362 // Add the cost features 363 for (size_t I = 0; 364 I < static_cast<size_t>(InlineCostFeatureIndex::NumberOfFeatures); ++I) { 365 *ModelRunner->getTensor<int64_t>(inlineCostFeatureToMlFeature( 366 static_cast<InlineCostFeatureIndex>(I))) = CostFeatures->at(I); 367 } 368 369 return getAdviceFromModel(CB, ORE); 370 } 371 372 std::unique_ptr<MLInlineAdvice> 373 MLInlineAdvisor::getAdviceFromModel(CallBase &CB, 374 OptimizationRemarkEmitter &ORE) { 375 return std::make_unique<MLInlineAdvice>( 376 this, CB, ORE, static_cast<bool>(ModelRunner->evaluate<int64_t>())); 377 } 378 379 std::unique_ptr<InlineAdvice> MLInlineAdvisor::getMandatoryAdvice(CallBase &CB, 380 bool Advice) { 381 // Make sure we track inlinings in all cases - mandatory or not. 382 if (Advice && !ForceStop) 383 return getMandatoryAdviceImpl(CB); 384 385 // If this is a "never inline" case, there won't be any changes to internal 386 // state we need to track, so we can just return the base InlineAdvice, which 387 // will do nothing interesting. 388 // Same if we are forced to stop - we don't track anymore. 389 return std::make_unique<InlineAdvice>(this, CB, getCallerORE(CB), Advice); 390 } 391 392 std::unique_ptr<MLInlineAdvice> 393 MLInlineAdvisor::getMandatoryAdviceImpl(CallBase &CB) { 394 return std::make_unique<MLInlineAdvice>(this, CB, getCallerORE(CB), true); 395 } 396 397 void MLInlineAdvisor::print(raw_ostream &OS) const { 398 OS << "[MLInlineAdvisor] Nodes: " << NodeCount << " Edges: " << EdgeCount 399 << " EdgesOfLastSeenNodes: " << EdgesOfLastSeenNodes << "\n"; 400 OS << "[MLInlineAdvisor] FPI:\n"; 401 for (auto I : FPICache) { 402 OS << I.getFirst()->getName() << ":\n"; 403 I.getSecond().print(OS); 404 OS << "\n"; 405 } 406 OS << "\n"; 407 } 408 409 MLInlineAdvice::MLInlineAdvice(MLInlineAdvisor *Advisor, CallBase &CB, 410 OptimizationRemarkEmitter &ORE, 411 bool Recommendation) 412 : InlineAdvice(Advisor, CB, ORE, Recommendation), 413 CallerIRSize(Advisor->isForcedToStop() ? 0 : Advisor->getIRSize(*Caller)), 414 CalleeIRSize(Advisor->isForcedToStop() ? 0 : Advisor->getIRSize(*Callee)), 415 CallerAndCalleeEdges(Advisor->isForcedToStop() 416 ? 0 417 : (Advisor->getLocalCalls(*Caller) + 418 Advisor->getLocalCalls(*Callee))), 419 PreInlineCallerFPI(Advisor->getCachedFPI(*Caller)) { 420 if (Recommendation) 421 FPU.emplace(Advisor->getCachedFPI(*getCaller()), CB); 422 } 423 424 void MLInlineAdvice::reportContextForRemark( 425 DiagnosticInfoOptimizationBase &OR) { 426 using namespace ore; 427 OR << NV("Callee", Callee->getName()); 428 for (size_t I = 0; I < NumberOfFeatures; ++I) 429 OR << NV(FeatureMap[I].name(), 430 *getAdvisor()->getModelRunner().getTensor<int64_t>(I)); 431 OR << NV("ShouldInline", isInliningRecommended()); 432 } 433 434 void MLInlineAdvice::updateCachedCallerFPI(FunctionAnalysisManager &FAM) const { 435 FPU->finish(FAM); 436 } 437 438 void MLInlineAdvice::recordInliningImpl() { 439 ORE.emit([&]() { 440 OptimizationRemark R(DEBUG_TYPE, "InliningSuccess", DLoc, Block); 441 reportContextForRemark(R); 442 return R; 443 }); 444 getAdvisor()->onSuccessfulInlining(*this, /*CalleeWasDeleted*/ false); 445 } 446 447 void MLInlineAdvice::recordInliningWithCalleeDeletedImpl() { 448 ORE.emit([&]() { 449 OptimizationRemark R(DEBUG_TYPE, "InliningSuccessWithCalleeDeleted", DLoc, 450 Block); 451 reportContextForRemark(R); 452 return R; 453 }); 454 getAdvisor()->onSuccessfulInlining(*this, /*CalleeWasDeleted*/ true); 455 } 456 457 void MLInlineAdvice::recordUnsuccessfulInliningImpl( 458 const InlineResult &Result) { 459 getAdvisor()->getCachedFPI(*Caller) = PreInlineCallerFPI; 460 ORE.emit([&]() { 461 OptimizationRemarkMissed R(DEBUG_TYPE, "InliningAttemptedAndUnsuccessful", 462 DLoc, Block); 463 reportContextForRemark(R); 464 return R; 465 }); 466 } 467 void MLInlineAdvice::recordUnattemptedInliningImpl() { 468 assert(!FPU); 469 ORE.emit([&]() { 470 OptimizationRemarkMissed R(DEBUG_TYPE, "IniningNotAttempted", DLoc, Block); 471 reportContextForRemark(R); 472 return R; 473 }); 474 } 475