1 //===- LoopPassManager.cpp - Loop pass management -------------------------===// 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/Transforms/Scalar/LoopPassManager.h" 10 #include "llvm/Analysis/AssumptionCache.h" 11 #include "llvm/Analysis/BasicAliasAnalysis.h" 12 #include "llvm/Analysis/BlockFrequencyInfo.h" 13 #include "llvm/Analysis/BranchProbabilityInfo.h" 14 #include "llvm/Analysis/GlobalsModRef.h" 15 #include "llvm/Analysis/MemorySSA.h" 16 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 17 #include "llvm/Analysis/TargetLibraryInfo.h" 18 #include "llvm/Support/Debug.h" 19 #include "llvm/Support/TimeProfiler.h" 20 21 using namespace llvm; 22 23 namespace llvm { 24 25 /// Explicitly specialize the pass manager's run method to handle loop nest 26 /// structure updates. 27 PreservedAnalyses 28 PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, 29 LPMUpdater &>::run(Loop &L, LoopAnalysisManager &AM, 30 LoopStandardAnalysisResults &AR, LPMUpdater &U) { 31 // Runs loop-nest passes only when the current loop is a top-level one. 32 PreservedAnalyses PA = (L.isOutermost() && !LoopNestPasses.empty()) 33 ? runWithLoopNestPasses(L, AM, AR, U) 34 : runWithoutLoopNestPasses(L, AM, AR, U); 35 36 // Invalidation for the current loop should be handled above, and other loop 37 // analysis results shouldn't be impacted by runs over this loop. Therefore, 38 // the remaining analysis results in the AnalysisManager are preserved. We 39 // mark this with a set so that we don't need to inspect each one 40 // individually. 41 // FIXME: This isn't correct! This loop and all nested loops' analyses should 42 // be preserved, but unrolling should invalidate the parent loop's analyses. 43 PA.preserveSet<AllAnalysesOn<Loop>>(); 44 45 return PA; 46 } 47 48 void PassManager<Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, 49 LPMUpdater &>::printPipeline(raw_ostream &OS, 50 function_ref<StringRef(StringRef)> 51 MapClassName2PassName) { 52 assert(LoopPasses.size() + LoopNestPasses.size() == IsLoopNestPass.size()); 53 54 unsigned IdxLP = 0, IdxLNP = 0; 55 for (unsigned Idx = 0, Size = IsLoopNestPass.size(); Idx != Size; ++Idx) { 56 if (IsLoopNestPass[Idx]) { 57 auto *P = LoopNestPasses[IdxLNP++].get(); 58 P->printPipeline(OS, MapClassName2PassName); 59 } else { 60 auto *P = LoopPasses[IdxLP++].get(); 61 P->printPipeline(OS, MapClassName2PassName); 62 } 63 if (Idx + 1 < Size) 64 OS << ","; 65 } 66 } 67 68 // Run both loop passes and loop-nest passes on top-level loop \p L. 69 PreservedAnalyses 70 LoopPassManager::runWithLoopNestPasses(Loop &L, LoopAnalysisManager &AM, 71 LoopStandardAnalysisResults &AR, 72 LPMUpdater &U) { 73 assert(L.isOutermost() && 74 "Loop-nest passes should only run on top-level loops."); 75 PreservedAnalyses PA = PreservedAnalyses::all(); 76 77 // Request PassInstrumentation from analysis manager, will use it to run 78 // instrumenting callbacks for the passes later. 79 PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR); 80 81 unsigned LoopPassIndex = 0, LoopNestPassIndex = 0; 82 83 // `LoopNestPtr` points to the `LoopNest` object for the current top-level 84 // loop and `IsLoopNestPtrValid` indicates whether the pointer is still valid. 85 // The `LoopNest` object will have to be re-constructed if the pointer is 86 // invalid when encountering a loop-nest pass. 87 std::unique_ptr<LoopNest> LoopNestPtr; 88 bool IsLoopNestPtrValid = false; 89 90 for (size_t I = 0, E = IsLoopNestPass.size(); I != E; ++I) { 91 Optional<PreservedAnalyses> PassPA; 92 if (!IsLoopNestPass[I]) { 93 // The `I`-th pass is a loop pass. 94 auto &Pass = LoopPasses[LoopPassIndex++]; 95 PassPA = runSinglePass(L, Pass, AM, AR, U, PI); 96 } else { 97 // The `I`-th pass is a loop-nest pass. 98 auto &Pass = LoopNestPasses[LoopNestPassIndex++]; 99 100 // If the loop-nest object calculated before is no longer valid, 101 // re-calculate it here before running the loop-nest pass. 102 if (!IsLoopNestPtrValid) { 103 LoopNestPtr = LoopNest::getLoopNest(L, AR.SE); 104 IsLoopNestPtrValid = true; 105 } 106 PassPA = runSinglePass(*LoopNestPtr, Pass, AM, AR, U, PI); 107 } 108 109 // `PassPA` is `None` means that the before-pass callbacks in 110 // `PassInstrumentation` return false. The pass does not run in this case, 111 // so we can skip the following procedure. 112 if (!PassPA) 113 continue; 114 115 // If the loop was deleted, abort the run and return to the outer walk. 116 if (U.skipCurrentLoop()) { 117 PA.intersect(std::move(*PassPA)); 118 break; 119 } 120 121 // Update the analysis manager as each pass runs and potentially 122 // invalidates analyses. 123 AM.invalidate(L, *PassPA); 124 125 // Finally, we intersect the final preserved analyses to compute the 126 // aggregate preserved set for this pass manager. 127 PA.intersect(std::move(*PassPA)); 128 129 // Check if the current pass preserved the loop-nest object or not. 130 IsLoopNestPtrValid &= PassPA->getChecker<LoopNestAnalysis>().preserved(); 131 132 // After running the loop pass, the parent loop might change and we need to 133 // notify the updater, otherwise U.ParentL might gets outdated and triggers 134 // assertion failures in addSiblingLoops and addChildLoops. 135 U.setParentLoop(L.getParentLoop()); 136 } 137 return PA; 138 } 139 140 // Run all loop passes on loop \p L. Loop-nest passes don't run either because 141 // \p L is not a top-level one or simply because there are no loop-nest passes 142 // in the pass manager at all. 143 PreservedAnalyses 144 LoopPassManager::runWithoutLoopNestPasses(Loop &L, LoopAnalysisManager &AM, 145 LoopStandardAnalysisResults &AR, 146 LPMUpdater &U) { 147 PreservedAnalyses PA = PreservedAnalyses::all(); 148 149 // Request PassInstrumentation from analysis manager, will use it to run 150 // instrumenting callbacks for the passes later. 151 PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(L, AR); 152 for (auto &Pass : LoopPasses) { 153 Optional<PreservedAnalyses> PassPA = runSinglePass(L, Pass, AM, AR, U, PI); 154 155 // `PassPA` is `None` means that the before-pass callbacks in 156 // `PassInstrumentation` return false. The pass does not run in this case, 157 // so we can skip the following procedure. 158 if (!PassPA) 159 continue; 160 161 // If the loop was deleted, abort the run and return to the outer walk. 162 if (U.skipCurrentLoop()) { 163 PA.intersect(std::move(*PassPA)); 164 break; 165 } 166 167 // Update the analysis manager as each pass runs and potentially 168 // invalidates analyses. 169 AM.invalidate(L, *PassPA); 170 171 // Finally, we intersect the final preserved analyses to compute the 172 // aggregate preserved set for this pass manager. 173 PA.intersect(std::move(*PassPA)); 174 175 // After running the loop pass, the parent loop might change and we need to 176 // notify the updater, otherwise U.ParentL might gets outdated and triggers 177 // assertion failures in addSiblingLoops and addChildLoops. 178 U.setParentLoop(L.getParentLoop()); 179 } 180 return PA; 181 } 182 } // namespace llvm 183 184 void FunctionToLoopPassAdaptor::printPipeline( 185 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) { 186 OS << (UseMemorySSA ? "loop-mssa(" : "loop("); 187 Pass->printPipeline(OS, MapClassName2PassName); 188 OS << ")"; 189 } 190 PreservedAnalyses FunctionToLoopPassAdaptor::run(Function &F, 191 FunctionAnalysisManager &AM) { 192 // Before we even compute any loop analyses, first run a miniature function 193 // pass pipeline to put loops into their canonical form. Note that we can 194 // directly build up function analyses after this as the function pass 195 // manager handles all the invalidation at that layer. 196 PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(F); 197 198 PreservedAnalyses PA = PreservedAnalyses::all(); 199 // Check the PassInstrumentation's BeforePass callbacks before running the 200 // canonicalization pipeline. 201 if (PI.runBeforePass<Function>(LoopCanonicalizationFPM, F)) { 202 PA = LoopCanonicalizationFPM.run(F, AM); 203 PI.runAfterPass<Function>(LoopCanonicalizationFPM, F, PA); 204 } 205 206 // Get the loop structure for this function 207 LoopInfo &LI = AM.getResult<LoopAnalysis>(F); 208 209 // If there are no loops, there is nothing to do here. 210 if (LI.empty()) 211 return PA; 212 213 // Get the analysis results needed by loop passes. 214 MemorySSA *MSSA = 215 UseMemorySSA ? (&AM.getResult<MemorySSAAnalysis>(F).getMSSA()) : nullptr; 216 BlockFrequencyInfo *BFI = UseBlockFrequencyInfo && F.hasProfileData() 217 ? (&AM.getResult<BlockFrequencyAnalysis>(F)) 218 : nullptr; 219 BranchProbabilityInfo *BPI = 220 UseBranchProbabilityInfo && F.hasProfileData() 221 ? (&AM.getResult<BranchProbabilityAnalysis>(F)) 222 : nullptr; 223 LoopStandardAnalysisResults LAR = {AM.getResult<AAManager>(F), 224 AM.getResult<AssumptionAnalysis>(F), 225 AM.getResult<DominatorTreeAnalysis>(F), 226 AM.getResult<LoopAnalysis>(F), 227 AM.getResult<ScalarEvolutionAnalysis>(F), 228 AM.getResult<TargetLibraryAnalysis>(F), 229 AM.getResult<TargetIRAnalysis>(F), 230 BFI, 231 BPI, 232 MSSA}; 233 234 // Setup the loop analysis manager from its proxy. It is important that 235 // this is only done when there are loops to process and we have built the 236 // LoopStandardAnalysisResults object. The loop analyses cached in this 237 // manager have access to those analysis results and so it must invalidate 238 // itself when they go away. 239 auto &LAMFP = AM.getResult<LoopAnalysisManagerFunctionProxy>(F); 240 if (UseMemorySSA) 241 LAMFP.markMSSAUsed(); 242 LoopAnalysisManager &LAM = LAMFP.getManager(); 243 244 // A postorder worklist of loops to process. 245 SmallPriorityWorklist<Loop *, 4> Worklist; 246 247 // Register the worklist and loop analysis manager so that loop passes can 248 // update them when they mutate the loop nest structure. 249 LPMUpdater Updater(Worklist, LAM, LoopNestMode); 250 251 // Add the loop nests in the reverse order of LoopInfo. See method 252 // declaration. 253 if (!LoopNestMode) { 254 appendLoopsToWorklist(LI, Worklist); 255 } else { 256 for (Loop *L : LI) 257 Worklist.insert(L); 258 } 259 260 #ifndef NDEBUG 261 PI.pushBeforeNonSkippedPassCallback([&LAR, &LI](StringRef PassID, Any IR) { 262 if (isSpecialPass(PassID, {"PassManager"})) 263 return; 264 assert(any_isa<const Loop *>(IR) || any_isa<const LoopNest *>(IR)); 265 const Loop *L = any_isa<const Loop *>(IR) 266 ? any_cast<const Loop *>(IR) 267 : &any_cast<const LoopNest *>(IR)->getOutermostLoop(); 268 assert(L && "Loop should be valid for printing"); 269 270 // Verify the loop structure and LCSSA form before visiting the loop. 271 L->verifyLoop(); 272 assert(L->isRecursivelyLCSSAForm(LAR.DT, LI) && 273 "Loops must remain in LCSSA form!"); 274 }); 275 #endif 276 277 do { 278 Loop *L = Worklist.pop_back_val(); 279 assert(!(LoopNestMode && L->getParentLoop()) && 280 "L should be a top-level loop in loop-nest mode."); 281 282 // Reset the update structure for this loop. 283 Updater.CurrentL = L; 284 Updater.SkipCurrentLoop = false; 285 286 #ifndef NDEBUG 287 // Save a parent loop pointer for asserts. 288 Updater.ParentL = L->getParentLoop(); 289 #endif 290 // Check the PassInstrumentation's BeforePass callbacks before running the 291 // pass, skip its execution completely if asked to (callback returns 292 // false). 293 if (!PI.runBeforePass<Loop>(*Pass, *L)) 294 continue; 295 296 PreservedAnalyses PassPA; 297 { 298 TimeTraceScope TimeScope(Pass->name()); 299 PassPA = Pass->run(*L, LAM, LAR, Updater); 300 } 301 302 // Do not pass deleted Loop into the instrumentation. 303 if (Updater.skipCurrentLoop()) 304 PI.runAfterPassInvalidated<Loop>(*Pass, PassPA); 305 else 306 PI.runAfterPass<Loop>(*Pass, *L, PassPA); 307 308 if (LAR.MSSA && !PassPA.getChecker<MemorySSAAnalysis>().preserved()) 309 report_fatal_error("Loop pass manager using MemorySSA contains a pass " 310 "that does not preserve MemorySSA"); 311 312 #ifndef NDEBUG 313 // LoopAnalysisResults should always be valid. 314 // Note that we don't LAR.SE.verify() because that can change observed SE 315 // queries. See PR44815. 316 if (VerifyDomInfo) 317 LAR.DT.verify(); 318 if (VerifyLoopInfo) 319 LAR.LI.verify(LAR.DT); 320 if (LAR.MSSA && VerifyMemorySSA) 321 LAR.MSSA->verifyMemorySSA(); 322 #endif 323 324 // If the loop hasn't been deleted, we need to handle invalidation here. 325 if (!Updater.skipCurrentLoop()) 326 // We know that the loop pass couldn't have invalidated any other 327 // loop's analyses (that's the contract of a loop pass), so directly 328 // handle the loop analysis manager's invalidation here. 329 LAM.invalidate(*L, PassPA); 330 331 // Then intersect the preserved set so that invalidation of module 332 // analyses will eventually occur when the module pass completes. 333 PA.intersect(std::move(PassPA)); 334 } while (!Worklist.empty()); 335 336 #ifndef NDEBUG 337 PI.popBeforeNonSkippedPassCallback(); 338 #endif 339 340 // By definition we preserve the proxy. We also preserve all analyses on 341 // Loops. This precludes *any* invalidation of loop analyses by the proxy, 342 // but that's OK because we've taken care to invalidate analyses in the 343 // loop analysis manager incrementally above. 344 PA.preserveSet<AllAnalysesOn<Loop>>(); 345 PA.preserve<LoopAnalysisManagerFunctionProxy>(); 346 // We also preserve the set of standard analyses. 347 PA.preserve<DominatorTreeAnalysis>(); 348 PA.preserve<LoopAnalysis>(); 349 PA.preserve<ScalarEvolutionAnalysis>(); 350 if (UseBlockFrequencyInfo && F.hasProfileData()) 351 PA.preserve<BlockFrequencyAnalysis>(); 352 if (UseBranchProbabilityInfo && F.hasProfileData()) 353 PA.preserve<BranchProbabilityAnalysis>(); 354 if (UseMemorySSA) 355 PA.preserve<MemorySSAAnalysis>(); 356 return PA; 357 } 358 359 PrintLoopPass::PrintLoopPass() : OS(dbgs()) {} 360 PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner) 361 : OS(OS), Banner(Banner) {} 362 363 PreservedAnalyses PrintLoopPass::run(Loop &L, LoopAnalysisManager &, 364 LoopStandardAnalysisResults &, 365 LPMUpdater &) { 366 printLoop(L, OS, Banner); 367 return PreservedAnalyses::all(); 368 } 369