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