1 //===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===// 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 #include "llvm/Analysis/CGSCCPassManager.h" 10 #include "llvm/ADT/ArrayRef.h" 11 #include "llvm/ADT/Optional.h" 12 #include "llvm/ADT/STLExtras.h" 13 #include "llvm/ADT/SetVector.h" 14 #include "llvm/ADT/SmallPtrSet.h" 15 #include "llvm/ADT/SmallVector.h" 16 #include "llvm/ADT/iterator_range.h" 17 #include "llvm/Analysis/LazyCallGraph.h" 18 #include "llvm/IR/Constant.h" 19 #include "llvm/IR/InstIterator.h" 20 #include "llvm/IR/Instruction.h" 21 #include "llvm/IR/PassManager.h" 22 #include "llvm/IR/PassManagerImpl.h" 23 #include "llvm/Support/Casting.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Support/TimeProfiler.h" 27 #include <algorithm> 28 #include <cassert> 29 #include <iterator> 30 31 #define DEBUG_TYPE "cgscc" 32 33 using namespace llvm; 34 35 // Explicit template instantiations and specialization definitions for core 36 // template typedefs. 37 namespace llvm { 38 39 // Explicit instantiations for the core proxy templates. 40 template class AllAnalysesOn<LazyCallGraph::SCC>; 41 template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>; 42 template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, 43 LazyCallGraph &, CGSCCUpdateResult &>; 44 template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>; 45 template class OuterAnalysisManagerProxy<ModuleAnalysisManager, 46 LazyCallGraph::SCC, LazyCallGraph &>; 47 template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>; 48 49 /// Explicitly specialize the pass manager run method to handle call graph 50 /// updates. 51 template <> 52 PreservedAnalyses 53 PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, 54 CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC, 55 CGSCCAnalysisManager &AM, 56 LazyCallGraph &G, CGSCCUpdateResult &UR) { 57 // Request PassInstrumentation from analysis manager, will use it to run 58 // instrumenting callbacks for the passes later. 59 PassInstrumentation PI = 60 AM.getResult<PassInstrumentationAnalysis>(InitialC, G); 61 62 PreservedAnalyses PA = PreservedAnalyses::all(); 63 64 if (DebugLogging) 65 dbgs() << "Starting CGSCC pass manager run.\n"; 66 67 // The SCC may be refined while we are running passes over it, so set up 68 // a pointer that we can update. 69 LazyCallGraph::SCC *C = &InitialC; 70 71 // Get Function analysis manager from its proxy. 72 FunctionAnalysisManager &FAM = 73 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*C)->getManager(); 74 75 for (auto &Pass : Passes) { 76 // Check the PassInstrumentation's BeforePass callbacks before running the 77 // pass, skip its execution completely if asked to (callback returns false). 78 if (!PI.runBeforePass(*Pass, *C)) 79 continue; 80 81 PreservedAnalyses PassPA; 82 { 83 TimeTraceScope TimeScope(Pass->name()); 84 PassPA = Pass->run(*C, AM, G, UR); 85 } 86 87 if (UR.InvalidatedSCCs.count(C)) 88 PI.runAfterPassInvalidated<LazyCallGraph::SCC>(*Pass, PassPA); 89 else 90 PI.runAfterPass<LazyCallGraph::SCC>(*Pass, *C, PassPA); 91 92 // Update the SCC if necessary. 93 C = UR.UpdatedC ? UR.UpdatedC : C; 94 if (UR.UpdatedC) { 95 // If C is updated, also create a proxy and update FAM inside the result. 96 auto *ResultFAMCP = 97 &AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G); 98 ResultFAMCP->updateFAM(FAM); 99 } 100 101 // If the CGSCC pass wasn't able to provide a valid updated SCC, the 102 // current SCC may simply need to be skipped if invalid. 103 if (UR.InvalidatedSCCs.count(C)) { 104 LLVM_DEBUG(dbgs() << "Skipping invalidated root or island SCC!\n"); 105 break; 106 } 107 // Check that we didn't miss any update scenario. 108 assert(C->begin() != C->end() && "Cannot have an empty SCC!"); 109 110 // Update the analysis manager as each pass runs and potentially 111 // invalidates analyses. 112 AM.invalidate(*C, PassPA); 113 114 // Finally, we intersect the final preserved analyses to compute the 115 // aggregate preserved set for this pass manager. 116 PA.intersect(std::move(PassPA)); 117 118 // FIXME: Historically, the pass managers all called the LLVM context's 119 // yield function here. We don't have a generic way to acquire the 120 // context and it isn't yet clear what the right pattern is for yielding 121 // in the new pass manager so it is currently omitted. 122 // ...getContext().yield(); 123 } 124 125 // Before we mark all of *this* SCC's analyses as preserved below, intersect 126 // this with the cross-SCC preserved analysis set. This is used to allow 127 // CGSCC passes to mutate ancestor SCCs and still trigger proper invalidation 128 // for them. 129 UR.CrossSCCPA.intersect(PA); 130 131 // Invalidation was handled after each pass in the above loop for the current 132 // SCC. Therefore, the remaining analysis results in the AnalysisManager are 133 // preserved. We mark this with a set so that we don't need to inspect each 134 // one individually. 135 PA.preserveSet<AllAnalysesOn<LazyCallGraph::SCC>>(); 136 137 if (DebugLogging) 138 dbgs() << "Finished CGSCC pass manager run.\n"; 139 140 return PA; 141 } 142 143 bool CGSCCAnalysisManagerModuleProxy::Result::invalidate( 144 Module &M, const PreservedAnalyses &PA, 145 ModuleAnalysisManager::Invalidator &Inv) { 146 // If literally everything is preserved, we're done. 147 if (PA.areAllPreserved()) 148 return false; // This is still a valid proxy. 149 150 // If this proxy or the call graph is going to be invalidated, we also need 151 // to clear all the keys coming from that analysis. 152 // 153 // We also directly invalidate the FAM's module proxy if necessary, and if 154 // that proxy isn't preserved we can't preserve this proxy either. We rely on 155 // it to handle module -> function analysis invalidation in the face of 156 // structural changes and so if it's unavailable we conservatively clear the 157 // entire SCC layer as well rather than trying to do invalidation ourselves. 158 auto PAC = PA.getChecker<CGSCCAnalysisManagerModuleProxy>(); 159 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>()) || 160 Inv.invalidate<LazyCallGraphAnalysis>(M, PA) || 161 Inv.invalidate<FunctionAnalysisManagerModuleProxy>(M, PA)) { 162 InnerAM->clear(); 163 164 // And the proxy itself should be marked as invalid so that we can observe 165 // the new call graph. This isn't strictly necessary because we cheat 166 // above, but is still useful. 167 return true; 168 } 169 170 // Directly check if the relevant set is preserved so we can short circuit 171 // invalidating SCCs below. 172 bool AreSCCAnalysesPreserved = 173 PA.allAnalysesInSetPreserved<AllAnalysesOn<LazyCallGraph::SCC>>(); 174 175 // Ok, we have a graph, so we can propagate the invalidation down into it. 176 G->buildRefSCCs(); 177 for (auto &RC : G->postorder_ref_sccs()) 178 for (auto &C : RC) { 179 Optional<PreservedAnalyses> InnerPA; 180 181 // Check to see whether the preserved set needs to be adjusted based on 182 // module-level analysis invalidation triggering deferred invalidation 183 // for this SCC. 184 if (auto *OuterProxy = 185 InnerAM->getCachedResult<ModuleAnalysisManagerCGSCCProxy>(C)) 186 for (const auto &OuterInvalidationPair : 187 OuterProxy->getOuterInvalidations()) { 188 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first; 189 const auto &InnerAnalysisIDs = OuterInvalidationPair.second; 190 if (Inv.invalidate(OuterAnalysisID, M, PA)) { 191 if (!InnerPA) 192 InnerPA = PA; 193 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs) 194 InnerPA->abandon(InnerAnalysisID); 195 } 196 } 197 198 // Check if we needed a custom PA set. If so we'll need to run the inner 199 // invalidation. 200 if (InnerPA) { 201 InnerAM->invalidate(C, *InnerPA); 202 continue; 203 } 204 205 // Otherwise we only need to do invalidation if the original PA set didn't 206 // preserve all SCC analyses. 207 if (!AreSCCAnalysesPreserved) 208 InnerAM->invalidate(C, PA); 209 } 210 211 // Return false to indicate that this result is still a valid proxy. 212 return false; 213 } 214 215 template <> 216 CGSCCAnalysisManagerModuleProxy::Result 217 CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM) { 218 // Force the Function analysis manager to also be available so that it can 219 // be accessed in an SCC analysis and proxied onward to function passes. 220 // FIXME: It is pretty awkward to just drop the result here and assert that 221 // we can find it again later. 222 (void)AM.getResult<FunctionAnalysisManagerModuleProxy>(M); 223 224 return Result(*InnerAM, AM.getResult<LazyCallGraphAnalysis>(M)); 225 } 226 227 AnalysisKey FunctionAnalysisManagerCGSCCProxy::Key; 228 229 FunctionAnalysisManagerCGSCCProxy::Result 230 FunctionAnalysisManagerCGSCCProxy::run(LazyCallGraph::SCC &C, 231 CGSCCAnalysisManager &AM, 232 LazyCallGraph &CG) { 233 // Note: unconditionally getting checking that the proxy exists may get it at 234 // this point. There are cases when this is being run unnecessarily, but 235 // it is cheap and having the assertion in place is more valuable. 236 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerCGSCCProxy>(C, CG); 237 Module &M = *C.begin()->getFunction().getParent(); 238 bool ProxyExists = 239 MAMProxy.cachedResultExists<FunctionAnalysisManagerModuleProxy>(M); 240 assert(ProxyExists && 241 "The CGSCC pass manager requires that the FAM module proxy is run " 242 "on the module prior to entering the CGSCC walk"); 243 (void)ProxyExists; 244 245 // We just return an empty result. The caller will use the updateFAM interface 246 // to correctly register the relevant FunctionAnalysisManager based on the 247 // context in which this proxy is run. 248 return Result(); 249 } 250 251 bool FunctionAnalysisManagerCGSCCProxy::Result::invalidate( 252 LazyCallGraph::SCC &C, const PreservedAnalyses &PA, 253 CGSCCAnalysisManager::Invalidator &Inv) { 254 // If literally everything is preserved, we're done. 255 if (PA.areAllPreserved()) 256 return false; // This is still a valid proxy. 257 258 // All updates to preserve valid results are done below, so we don't need to 259 // invalidate this proxy. 260 // 261 // Note that in order to preserve this proxy, a module pass must ensure that 262 // the FAM has been completely updated to handle the deletion of functions. 263 // Specifically, any FAM-cached results for those functions need to have been 264 // forcibly cleared. When preserved, this proxy will only invalidate results 265 // cached on functions *still in the module* at the end of the module pass. 266 auto PAC = PA.getChecker<FunctionAnalysisManagerCGSCCProxy>(); 267 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<LazyCallGraph::SCC>>()) { 268 for (LazyCallGraph::Node &N : C) 269 FAM->clear(N.getFunction(), N.getFunction().getName()); 270 271 return false; 272 } 273 274 // Directly check if the relevant set is preserved. 275 bool AreFunctionAnalysesPreserved = 276 PA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>(); 277 278 // Now walk all the functions to see if any inner analysis invalidation is 279 // necessary. 280 for (LazyCallGraph::Node &N : C) { 281 Function &F = N.getFunction(); 282 Optional<PreservedAnalyses> FunctionPA; 283 284 // Check to see whether the preserved set needs to be pruned based on 285 // SCC-level analysis invalidation that triggers deferred invalidation 286 // registered with the outer analysis manager proxy for this function. 287 if (auto *OuterProxy = 288 FAM->getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F)) 289 for (const auto &OuterInvalidationPair : 290 OuterProxy->getOuterInvalidations()) { 291 AnalysisKey *OuterAnalysisID = OuterInvalidationPair.first; 292 const auto &InnerAnalysisIDs = OuterInvalidationPair.second; 293 if (Inv.invalidate(OuterAnalysisID, C, PA)) { 294 if (!FunctionPA) 295 FunctionPA = PA; 296 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs) 297 FunctionPA->abandon(InnerAnalysisID); 298 } 299 } 300 301 // Check if we needed a custom PA set, and if so we'll need to run the 302 // inner invalidation. 303 if (FunctionPA) { 304 FAM->invalidate(F, *FunctionPA); 305 continue; 306 } 307 308 // Otherwise we only need to do invalidation if the original PA set didn't 309 // preserve all function analyses. 310 if (!AreFunctionAnalysesPreserved) 311 FAM->invalidate(F, PA); 312 } 313 314 // Return false to indicate that this result is still a valid proxy. 315 return false; 316 } 317 318 } // end namespace llvm 319 320 /// When a new SCC is created for the graph we first update the 321 /// FunctionAnalysisManager in the Proxy's result. 322 /// As there might be function analysis results cached for the functions now in 323 /// that SCC, two forms of updates are required. 324 /// 325 /// First, a proxy from the SCC to the FunctionAnalysisManager needs to be 326 /// created so that any subsequent invalidation events to the SCC are 327 /// propagated to the function analysis results cached for functions within it. 328 /// 329 /// Second, if any of the functions within the SCC have analysis results with 330 /// outer analysis dependencies, then those dependencies would point to the 331 /// *wrong* SCC's analysis result. We forcibly invalidate the necessary 332 /// function analyses so that they don't retain stale handles. 333 static void updateNewSCCFunctionAnalyses(LazyCallGraph::SCC &C, 334 LazyCallGraph &G, 335 CGSCCAnalysisManager &AM, 336 FunctionAnalysisManager &FAM) { 337 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, G).updateFAM(FAM); 338 339 // Now walk the functions in this SCC and invalidate any function analysis 340 // results that might have outer dependencies on an SCC analysis. 341 for (LazyCallGraph::Node &N : C) { 342 Function &F = N.getFunction(); 343 344 auto *OuterProxy = 345 FAM.getCachedResult<CGSCCAnalysisManagerFunctionProxy>(F); 346 if (!OuterProxy) 347 // No outer analyses were queried, nothing to do. 348 continue; 349 350 // Forcibly abandon all the inner analyses with dependencies, but 351 // invalidate nothing else. 352 auto PA = PreservedAnalyses::all(); 353 for (const auto &OuterInvalidationPair : 354 OuterProxy->getOuterInvalidations()) { 355 const auto &InnerAnalysisIDs = OuterInvalidationPair.second; 356 for (AnalysisKey *InnerAnalysisID : InnerAnalysisIDs) 357 PA.abandon(InnerAnalysisID); 358 } 359 360 // Now invalidate anything we found. 361 FAM.invalidate(F, PA); 362 } 363 } 364 365 /// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c 366 /// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly 367 /// added SCCs. 368 /// 369 /// The range of new SCCs must be in postorder already. The SCC they were split 370 /// out of must be provided as \p C. The current node being mutated and 371 /// triggering updates must be passed as \p N. 372 /// 373 /// This function returns the SCC containing \p N. This will be either \p C if 374 /// no new SCCs have been split out, or it will be the new SCC containing \p N. 375 template <typename SCCRangeT> 376 static LazyCallGraph::SCC * 377 incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G, 378 LazyCallGraph::Node &N, LazyCallGraph::SCC *C, 379 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR) { 380 using SCC = LazyCallGraph::SCC; 381 382 if (NewSCCRange.begin() == NewSCCRange.end()) 383 return C; 384 385 // Add the current SCC to the worklist as its shape has changed. 386 UR.CWorklist.insert(C); 387 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist:" << *C 388 << "\n"); 389 390 SCC *OldC = C; 391 392 // Update the current SCC. Note that if we have new SCCs, this must actually 393 // change the SCC. 394 assert(C != &*NewSCCRange.begin() && 395 "Cannot insert new SCCs without changing current SCC!"); 396 C = &*NewSCCRange.begin(); 397 assert(G.lookupSCC(N) == C && "Failed to update current SCC!"); 398 399 // If we had a cached FAM proxy originally, we will want to create more of 400 // them for each SCC that was split off. 401 FunctionAnalysisManager *FAM = nullptr; 402 if (auto *FAMProxy = 403 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>(*OldC)) 404 FAM = &FAMProxy->getManager(); 405 406 // We need to propagate an invalidation call to all but the newly current SCC 407 // because the outer pass manager won't do that for us after splitting them. 408 // FIXME: We should accept a PreservedAnalysis from the CG updater so that if 409 // there are preserved analysis we can avoid invalidating them here for 410 // split-off SCCs. 411 // We know however that this will preserve any FAM proxy so go ahead and mark 412 // that. 413 PreservedAnalyses PA; 414 PA.preserve<FunctionAnalysisManagerCGSCCProxy>(); 415 AM.invalidate(*OldC, PA); 416 417 // Ensure the now-current SCC's function analyses are updated. 418 if (FAM) 419 updateNewSCCFunctionAnalyses(*C, G, AM, *FAM); 420 421 for (SCC &NewC : llvm::reverse(make_range(std::next(NewSCCRange.begin()), 422 NewSCCRange.end()))) { 423 assert(C != &NewC && "No need to re-visit the current SCC!"); 424 assert(OldC != &NewC && "Already handled the original SCC!"); 425 UR.CWorklist.insert(&NewC); 426 LLVM_DEBUG(dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n"); 427 428 // Ensure new SCCs' function analyses are updated. 429 if (FAM) 430 updateNewSCCFunctionAnalyses(NewC, G, AM, *FAM); 431 432 // Also propagate a normal invalidation to the new SCC as only the current 433 // will get one from the pass manager infrastructure. 434 AM.invalidate(NewC, PA); 435 } 436 return C; 437 } 438 439 static LazyCallGraph::SCC &updateCGAndAnalysisManagerForPass( 440 LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N, 441 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, 442 FunctionAnalysisManager &FAM, bool FunctionPass) { 443 using Node = LazyCallGraph::Node; 444 using Edge = LazyCallGraph::Edge; 445 using SCC = LazyCallGraph::SCC; 446 using RefSCC = LazyCallGraph::RefSCC; 447 448 RefSCC &InitialRC = InitialC.getOuterRefSCC(); 449 SCC *C = &InitialC; 450 RefSCC *RC = &InitialRC; 451 Function &F = N.getFunction(); 452 453 // Walk the function body and build up the set of retained, promoted, and 454 // demoted edges. 455 SmallVector<Constant *, 16> Worklist; 456 SmallPtrSet<Constant *, 16> Visited; 457 SmallPtrSet<Node *, 16> RetainedEdges; 458 SmallSetVector<Node *, 4> PromotedRefTargets; 459 SmallSetVector<Node *, 4> DemotedCallTargets; 460 SmallSetVector<Node *, 4> NewCallEdges; 461 SmallSetVector<Node *, 4> NewRefEdges; 462 SmallSetVector<Node *, 4> NewNodes; 463 464 // First walk the function and handle all called functions. We do this first 465 // because if there is a single call edge, whether there are ref edges is 466 // irrelevant. 467 for (Instruction &I : instructions(F)) 468 if (auto *CB = dyn_cast<CallBase>(&I)) 469 if (Function *Callee = CB->getCalledFunction()) 470 if (Visited.insert(Callee).second && !Callee->isDeclaration()) { 471 Node *CalleeN = G.lookup(*Callee); 472 if (!CalleeN) { 473 CalleeN = &G.get(*Callee); 474 NewNodes.insert(CalleeN); 475 } 476 Edge *E = N->lookup(*CalleeN); 477 assert((E || !FunctionPass) && 478 "No function transformations should introduce *new* " 479 "call edges! Any new calls should be modeled as " 480 "promoted existing ref edges!"); 481 bool Inserted = RetainedEdges.insert(CalleeN).second; 482 (void)Inserted; 483 assert(Inserted && "We should never visit a function twice."); 484 if (!E) 485 NewCallEdges.insert(CalleeN); 486 else if (!E->isCall()) 487 PromotedRefTargets.insert(CalleeN); 488 } 489 490 // Now walk all references. 491 for (Instruction &I : instructions(F)) 492 for (Value *Op : I.operand_values()) 493 if (auto *C = dyn_cast<Constant>(Op)) 494 if (Visited.insert(C).second) 495 Worklist.push_back(C); 496 497 auto VisitRef = [&](Function &Referee) { 498 Node *RefereeN = G.lookup(Referee); 499 if (!RefereeN) { 500 RefereeN = &G.get(Referee); 501 NewNodes.insert(RefereeN); 502 } 503 Edge *E = N->lookup(*RefereeN); 504 assert((E || !FunctionPass) && 505 "No function transformations should introduce *new* ref " 506 "edges! Any new ref edges would require IPO which " 507 "function passes aren't allowed to do!"); 508 bool Inserted = RetainedEdges.insert(RefereeN).second; 509 (void)Inserted; 510 assert(Inserted && "We should never visit a function twice."); 511 if (!E) 512 NewRefEdges.insert(RefereeN); 513 else if (E->isCall()) 514 DemotedCallTargets.insert(RefereeN); 515 }; 516 LazyCallGraph::visitReferences(Worklist, Visited, VisitRef); 517 518 for (Node *NewNode : NewNodes) 519 G.initNode(*NewNode, *C); 520 521 // Handle new ref edges. 522 for (Node *RefTarget : NewRefEdges) { 523 SCC &TargetC = *G.lookupSCC(*RefTarget); 524 RefSCC &TargetRC = TargetC.getOuterRefSCC(); 525 (void)TargetRC; 526 // TODO: This only allows trivial edges to be added for now. 527 assert((RC == &TargetRC || 528 RC->isAncestorOf(TargetRC)) && "New ref edge is not trivial!"); 529 RC->insertTrivialRefEdge(N, *RefTarget); 530 } 531 532 // Handle new call edges. 533 for (Node *CallTarget : NewCallEdges) { 534 SCC &TargetC = *G.lookupSCC(*CallTarget); 535 RefSCC &TargetRC = TargetC.getOuterRefSCC(); 536 (void)TargetRC; 537 // TODO: This only allows trivial edges to be added for now. 538 assert((RC == &TargetRC || 539 RC->isAncestorOf(TargetRC)) && "New call edge is not trivial!"); 540 RC->insertTrivialCallEdge(N, *CallTarget); 541 } 542 543 // Include synthetic reference edges to known, defined lib functions. 544 for (auto *F : G.getLibFunctions()) 545 // While the list of lib functions doesn't have repeats, don't re-visit 546 // anything handled above. 547 if (!Visited.count(F)) 548 VisitRef(*F); 549 550 // First remove all of the edges that are no longer present in this function. 551 // The first step makes these edges uniformly ref edges and accumulates them 552 // into a separate data structure so removal doesn't invalidate anything. 553 SmallVector<Node *, 4> DeadTargets; 554 for (Edge &E : *N) { 555 if (RetainedEdges.count(&E.getNode())) 556 continue; 557 558 SCC &TargetC = *G.lookupSCC(E.getNode()); 559 RefSCC &TargetRC = TargetC.getOuterRefSCC(); 560 if (&TargetRC == RC && E.isCall()) { 561 if (C != &TargetC) { 562 // For separate SCCs this is trivial. 563 RC->switchTrivialInternalEdgeToRef(N, E.getNode()); 564 } else { 565 // Now update the call graph. 566 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, E.getNode()), 567 G, N, C, AM, UR); 568 } 569 } 570 571 // Now that this is ready for actual removal, put it into our list. 572 DeadTargets.push_back(&E.getNode()); 573 } 574 // Remove the easy cases quickly and actually pull them out of our list. 575 DeadTargets.erase( 576 llvm::remove_if(DeadTargets, 577 [&](Node *TargetN) { 578 SCC &TargetC = *G.lookupSCC(*TargetN); 579 RefSCC &TargetRC = TargetC.getOuterRefSCC(); 580 581 // We can't trivially remove internal targets, so skip 582 // those. 583 if (&TargetRC == RC) 584 return false; 585 586 RC->removeOutgoingEdge(N, *TargetN); 587 LLVM_DEBUG(dbgs() << "Deleting outgoing edge from '" 588 << N << "' to '" << TargetN << "'\n"); 589 return true; 590 }), 591 DeadTargets.end()); 592 593 // Now do a batch removal of the internal ref edges left. 594 auto NewRefSCCs = RC->removeInternalRefEdge(N, DeadTargets); 595 if (!NewRefSCCs.empty()) { 596 // The old RefSCC is dead, mark it as such. 597 UR.InvalidatedRefSCCs.insert(RC); 598 599 // Note that we don't bother to invalidate analyses as ref-edge 600 // connectivity is not really observable in any way and is intended 601 // exclusively to be used for ordering of transforms rather than for 602 // analysis conclusions. 603 604 // Update RC to the "bottom". 605 assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!"); 606 RC = &C->getOuterRefSCC(); 607 assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!"); 608 609 // The RC worklist is in reverse postorder, so we enqueue the new ones in 610 // RPO except for the one which contains the source node as that is the 611 // "bottom" we will continue processing in the bottom-up walk. 612 assert(NewRefSCCs.front() == RC && 613 "New current RefSCC not first in the returned list!"); 614 for (RefSCC *NewRC : llvm::reverse(make_range(std::next(NewRefSCCs.begin()), 615 NewRefSCCs.end()))) { 616 assert(NewRC != RC && "Should not encounter the current RefSCC further " 617 "in the postorder list of new RefSCCs."); 618 UR.RCWorklist.insert(NewRC); 619 LLVM_DEBUG(dbgs() << "Enqueuing a new RefSCC in the update worklist: " 620 << *NewRC << "\n"); 621 } 622 } 623 624 // Next demote all the call edges that are now ref edges. This helps make 625 // the SCCs small which should minimize the work below as we don't want to 626 // form cycles that this would break. 627 for (Node *RefTarget : DemotedCallTargets) { 628 SCC &TargetC = *G.lookupSCC(*RefTarget); 629 RefSCC &TargetRC = TargetC.getOuterRefSCC(); 630 631 // The easy case is when the target RefSCC is not this RefSCC. This is 632 // only supported when the target RefSCC is a child of this RefSCC. 633 if (&TargetRC != RC) { 634 assert(RC->isAncestorOf(TargetRC) && 635 "Cannot potentially form RefSCC cycles here!"); 636 RC->switchOutgoingEdgeToRef(N, *RefTarget); 637 LLVM_DEBUG(dbgs() << "Switch outgoing call edge to a ref edge from '" << N 638 << "' to '" << *RefTarget << "'\n"); 639 continue; 640 } 641 642 // We are switching an internal call edge to a ref edge. This may split up 643 // some SCCs. 644 if (C != &TargetC) { 645 // For separate SCCs this is trivial. 646 RC->switchTrivialInternalEdgeToRef(N, *RefTarget); 647 continue; 648 } 649 650 // Now update the call graph. 651 C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, *RefTarget), G, N, 652 C, AM, UR); 653 } 654 655 // Now promote ref edges into call edges. 656 for (Node *CallTarget : PromotedRefTargets) { 657 SCC &TargetC = *G.lookupSCC(*CallTarget); 658 RefSCC &TargetRC = TargetC.getOuterRefSCC(); 659 660 // The easy case is when the target RefSCC is not this RefSCC. This is 661 // only supported when the target RefSCC is a child of this RefSCC. 662 if (&TargetRC != RC) { 663 assert(RC->isAncestorOf(TargetRC) && 664 "Cannot potentially form RefSCC cycles here!"); 665 RC->switchOutgoingEdgeToCall(N, *CallTarget); 666 LLVM_DEBUG(dbgs() << "Switch outgoing ref edge to a call edge from '" << N 667 << "' to '" << *CallTarget << "'\n"); 668 continue; 669 } 670 LLVM_DEBUG(dbgs() << "Switch an internal ref edge to a call edge from '" 671 << N << "' to '" << *CallTarget << "'\n"); 672 673 // Otherwise we are switching an internal ref edge to a call edge. This 674 // may merge away some SCCs, and we add those to the UpdateResult. We also 675 // need to make sure to update the worklist in the event SCCs have moved 676 // before the current one in the post-order sequence 677 bool HasFunctionAnalysisProxy = false; 678 auto InitialSCCIndex = RC->find(*C) - RC->begin(); 679 bool FormedCycle = RC->switchInternalEdgeToCall( 680 N, *CallTarget, [&](ArrayRef<SCC *> MergedSCCs) { 681 for (SCC *MergedC : MergedSCCs) { 682 assert(MergedC != &TargetC && "Cannot merge away the target SCC!"); 683 684 HasFunctionAnalysisProxy |= 685 AM.getCachedResult<FunctionAnalysisManagerCGSCCProxy>( 686 *MergedC) != nullptr; 687 688 // Mark that this SCC will no longer be valid. 689 UR.InvalidatedSCCs.insert(MergedC); 690 691 // FIXME: We should really do a 'clear' here to forcibly release 692 // memory, but we don't have a good way of doing that and 693 // preserving the function analyses. 694 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>(); 695 PA.preserve<FunctionAnalysisManagerCGSCCProxy>(); 696 AM.invalidate(*MergedC, PA); 697 } 698 }); 699 700 // If we formed a cycle by creating this call, we need to update more data 701 // structures. 702 if (FormedCycle) { 703 C = &TargetC; 704 assert(G.lookupSCC(N) == C && "Failed to update current SCC!"); 705 706 // If one of the invalidated SCCs had a cached proxy to a function 707 // analysis manager, we need to create a proxy in the new current SCC as 708 // the invalidated SCCs had their functions moved. 709 if (HasFunctionAnalysisProxy) 710 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(*C, G).updateFAM(FAM); 711 712 // Any analyses cached for this SCC are no longer precise as the shape 713 // has changed by introducing this cycle. However, we have taken care to 714 // update the proxies so it remains valide. 715 auto PA = PreservedAnalyses::allInSet<AllAnalysesOn<Function>>(); 716 PA.preserve<FunctionAnalysisManagerCGSCCProxy>(); 717 AM.invalidate(*C, PA); 718 } 719 auto NewSCCIndex = RC->find(*C) - RC->begin(); 720 // If we have actually moved an SCC to be topologically "below" the current 721 // one due to merging, we will need to revisit the current SCC after 722 // visiting those moved SCCs. 723 // 724 // It is critical that we *do not* revisit the current SCC unless we 725 // actually move SCCs in the process of merging because otherwise we may 726 // form a cycle where an SCC is split apart, merged, split, merged and so 727 // on infinitely. 728 if (InitialSCCIndex < NewSCCIndex) { 729 // Put our current SCC back onto the worklist as we'll visit other SCCs 730 // that are now definitively ordered prior to the current one in the 731 // post-order sequence, and may end up observing more precise context to 732 // optimize the current SCC. 733 UR.CWorklist.insert(C); 734 LLVM_DEBUG(dbgs() << "Enqueuing the existing SCC in the worklist: " << *C 735 << "\n"); 736 // Enqueue in reverse order as we pop off the back of the worklist. 737 for (SCC &MovedC : llvm::reverse(make_range(RC->begin() + InitialSCCIndex, 738 RC->begin() + NewSCCIndex))) { 739 UR.CWorklist.insert(&MovedC); 740 LLVM_DEBUG(dbgs() << "Enqueuing a newly earlier in post-order SCC: " 741 << MovedC << "\n"); 742 } 743 } 744 } 745 746 assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!"); 747 assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!"); 748 assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!"); 749 750 // Record the current RefSCC and SCC for higher layers of the CGSCC pass 751 // manager now that all the updates have been applied. 752 if (RC != &InitialRC) 753 UR.UpdatedRC = RC; 754 if (C != &InitialC) 755 UR.UpdatedC = C; 756 757 return *C; 758 } 759 760 LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass( 761 LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N, 762 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, 763 FunctionAnalysisManager &FAM) { 764 return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM, 765 /* FunctionPass */ true); 766 } 767 LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForCGSCCPass( 768 LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N, 769 CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, 770 FunctionAnalysisManager &FAM) { 771 return updateCGAndAnalysisManagerForPass(G, InitialC, N, AM, UR, FAM, 772 /* FunctionPass */ false); 773 } 774