LoopPassManager.cpp 15 KB

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