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